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    point, size, AnyElement, AvailableSpace, Bounds, ContentMask, Element, ElementId,
  9    GlobalElementId, Hitbox, InteractiveElement, Interactivity, IntoElement, IsZero, LayoutId,
 10    ListSizingBehavior, Pixels, Render, ScrollHandle, Size, StyleRefinement, Styled, View,
 11    ViewContext, WindowContext,
 12};
 13use smallvec::SmallVec;
 14use std::{cell::RefCell, cmp, ops::Range, rc::Rc};
 15use taffy::style::Overflow;
 16
 17use super::ListHorizontalSizingBehavior;
 18
 19/// uniform_list provides lazy rendering for a set of items that are of uniform height.
 20/// When rendered into a container with overflow-y: hidden and a fixed (or max) height,
 21/// uniform_list will only render the visible subset of items.
 22#[track_caller]
 23pub fn uniform_list<I, R, V>(
 24    view: View<V>,
 25    id: I,
 26    item_count: usize,
 27    f: impl 'static + Fn(&mut V, Range<usize>, &mut ViewContext<V>) -> Vec<R>,
 28) -> UniformList
 29where
 30    I: Into<ElementId>,
 31    R: IntoElement,
 32    V: Render,
 33{
 34    let id = id.into();
 35    let mut base_style = StyleRefinement::default();
 36    base_style.overflow.y = Some(Overflow::Scroll);
 37
 38    let render_range = move |range, cx: &mut WindowContext| {
 39        view.update(cx, |this, cx| {
 40            f(this, range, cx)
 41                .into_iter()
 42                .map(|component| component.into_any_element())
 43                .collect()
 44        })
 45    };
 46
 47    UniformList {
 48        item_count,
 49        item_to_measure_index: 0,
 50        render_items: Box::new(render_range),
 51        decorations: Vec::new(),
 52        interactivity: Interactivity {
 53            element_id: Some(id),
 54            base_style: Box::new(base_style),
 55
 56            #[cfg(debug_assertions)]
 57            location: Some(*core::panic::Location::caller()),
 58
 59            ..Default::default()
 60        },
 61        scroll_handle: None,
 62        sizing_behavior: ListSizingBehavior::default(),
 63        horizontal_sizing_behavior: ListHorizontalSizingBehavior::default(),
 64    }
 65}
 66
 67/// A list element for efficiently laying out and displaying a list of uniform-height elements.
 68pub struct UniformList {
 69    item_count: usize,
 70    item_to_measure_index: usize,
 71    render_items:
 72        Box<dyn for<'a> Fn(Range<usize>, &'a mut WindowContext) -> SmallVec<[AnyElement; 64]>>,
 73    decorations: Vec<Box<dyn UniformListDecoration>>,
 74    interactivity: Interactivity,
 75    scroll_handle: Option<UniformListScrollHandle>,
 76    sizing_behavior: ListSizingBehavior,
 77    horizontal_sizing_behavior: ListHorizontalSizingBehavior,
 78}
 79
 80/// Frame state used by the [UniformList].
 81pub struct UniformListFrameState {
 82    items: SmallVec<[AnyElement; 32]>,
 83    decorations: SmallVec<[AnyElement; 1]>,
 84}
 85
 86/// A handle for controlling the scroll position of a uniform list.
 87/// This should be stored in your view and passed to the uniform_list on each frame.
 88#[derive(Clone, Debug, Default)]
 89pub struct UniformListScrollHandle(pub Rc<RefCell<UniformListScrollState>>);
 90
 91#[derive(Clone, Debug, Default)]
 92#[allow(missing_docs)]
 93pub struct UniformListScrollState {
 94    pub base_handle: ScrollHandle,
 95    pub deferred_scroll_to_item: Option<usize>,
 96    /// Size of the item, captured during last layout.
 97    pub last_item_size: Option<ItemSize>,
 98}
 99
100#[derive(Copy, Clone, Debug, Default)]
101/// The size of the item and its contents.
102pub struct ItemSize {
103    /// The size of the item.
104    pub item: Size<Pixels>,
105    /// The size of the item's contents, which may be larger than the item itself,
106    /// if the item was bounded by a parent element.
107    pub contents: Size<Pixels>,
108}
109
110impl UniformListScrollHandle {
111    /// Create a new scroll handle to bind to a uniform list.
112    pub fn new() -> Self {
113        Self(Rc::new(RefCell::new(UniformListScrollState {
114            base_handle: ScrollHandle::new(),
115            deferred_scroll_to_item: None,
116            last_item_size: None,
117        })))
118    }
119
120    /// Scroll the list to the given item index.
121    pub fn scroll_to_item(&self, ix: usize) {
122        self.0.borrow_mut().deferred_scroll_to_item = Some(ix);
123    }
124
125    /// Get the index of the topmost visible child.
126    pub fn logical_scroll_top_index(&self) -> usize {
127        let this = self.0.borrow();
128        this.deferred_scroll_to_item
129            .unwrap_or_else(|| this.base_handle.logical_scroll_top().0)
130    }
131}
132
133impl Styled for UniformList {
134    fn style(&mut self) -> &mut StyleRefinement {
135        &mut self.interactivity.base_style
136    }
137}
138
139impl Element for UniformList {
140    type RequestLayoutState = UniformListFrameState;
141    type PrepaintState = Option<Hitbox>;
142
143    fn id(&self) -> Option<ElementId> {
144        self.interactivity.element_id.clone()
145    }
146
147    fn request_layout(
148        &mut self,
149        global_id: Option<&GlobalElementId>,
150        cx: &mut WindowContext,
151    ) -> (LayoutId, Self::RequestLayoutState) {
152        let max_items = self.item_count;
153        let item_size = self.measure_item(None, cx);
154        let layout_id = self
155            .interactivity
156            .request_layout(global_id, cx, |style, cx| match self.sizing_behavior {
157                ListSizingBehavior::Infer => {
158                    cx.with_text_style(style.text_style().cloned(), |cx| {
159                        cx.request_measured_layout(
160                            style,
161                            move |known_dimensions, available_space, _cx| {
162                                let desired_height = item_size.height * max_items;
163                                let width = known_dimensions.width.unwrap_or(match available_space
164                                    .width
165                                {
166                                    AvailableSpace::Definite(x) => x,
167                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
168                                        item_size.width
169                                    }
170                                });
171                                let height = match available_space.height {
172                                    AvailableSpace::Definite(height) => desired_height.min(height),
173                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
174                                        desired_height
175                                    }
176                                };
177                                size(width, height)
178                            },
179                        )
180                    })
181                }
182                ListSizingBehavior::Auto => cx.with_text_style(style.text_style().cloned(), |cx| {
183                    cx.request_layout(style, None)
184                }),
185            });
186
187        (
188            layout_id,
189            UniformListFrameState {
190                items: SmallVec::new(),
191                decorations: SmallVec::new(),
192            },
193        )
194    }
195
196    fn prepaint(
197        &mut self,
198        global_id: Option<&GlobalElementId>,
199        bounds: Bounds<Pixels>,
200        frame_state: &mut Self::RequestLayoutState,
201        cx: &mut WindowContext,
202    ) -> Option<Hitbox> {
203        let style = self.interactivity.compute_style(global_id, None, cx);
204        let border = style.border_widths.to_pixels(cx.rem_size());
205        let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
206
207        let padded_bounds = Bounds::from_corners(
208            bounds.origin + point(border.left + padding.left, border.top + padding.top),
209            bounds.lower_right()
210                - point(border.right + padding.right, border.bottom + padding.bottom),
211        );
212
213        let can_scroll_horizontally = matches!(
214            self.horizontal_sizing_behavior,
215            ListHorizontalSizingBehavior::Unconstrained
216        );
217
218        let longest_item_size = self.measure_item(None, cx);
219        let content_width = if can_scroll_horizontally {
220            padded_bounds.size.width.max(longest_item_size.width)
221        } else {
222            padded_bounds.size.width
223        };
224        let content_size = Size {
225            width: content_width,
226            height: longest_item_size.height * self.item_count + padding.top + padding.bottom,
227        };
228
229        let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
230        let item_height = longest_item_size.height;
231        let shared_scroll_to_item = self.scroll_handle.as_mut().and_then(|handle| {
232            let mut handle = handle.0.borrow_mut();
233            handle.last_item_size = Some(ItemSize {
234                item: padded_bounds.size,
235                contents: content_size,
236            });
237            handle.deferred_scroll_to_item.take()
238        });
239
240        self.interactivity.prepaint(
241            global_id,
242            bounds,
243            content_size,
244            cx,
245            |style, mut scroll_offset, hitbox, cx| {
246                let border = style.border_widths.to_pixels(cx.rem_size());
247                let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
248
249                let padded_bounds = Bounds::from_corners(
250                    bounds.origin + point(border.left + padding.left, border.top),
251                    bounds.lower_right() - point(border.right + padding.right, border.bottom),
252                );
253
254                if let Some(handle) = self.scroll_handle.as_mut() {
255                    handle.0.borrow_mut().base_handle.set_bounds(bounds);
256                }
257
258                if self.item_count > 0 {
259                    let content_height =
260                        item_height * self.item_count + padding.top + padding.bottom;
261                    let is_scrolled_vertically = !scroll_offset.y.is_zero();
262                    let min_vertical_scroll_offset = padded_bounds.size.height - content_height;
263                    if is_scrolled_vertically && scroll_offset.y < min_vertical_scroll_offset {
264                        shared_scroll_offset.borrow_mut().y = min_vertical_scroll_offset;
265                        scroll_offset.y = min_vertical_scroll_offset;
266                    }
267
268                    let content_width = content_size.width + padding.left + padding.right;
269                    let is_scrolled_horizontally =
270                        can_scroll_horizontally && !scroll_offset.x.is_zero();
271                    if is_scrolled_horizontally && content_width <= padded_bounds.size.width {
272                        shared_scroll_offset.borrow_mut().x = Pixels::ZERO;
273                        scroll_offset.x = Pixels::ZERO;
274                    }
275
276                    if let Some(ix) = shared_scroll_to_item {
277                        let list_height = padded_bounds.size.height;
278                        let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
279                        let item_top = item_height * ix + padding.top;
280                        let item_bottom = item_top + item_height;
281                        let scroll_top = -updated_scroll_offset.y;
282                        if item_top < scroll_top + padding.top {
283                            updated_scroll_offset.y = -(item_top) + padding.top;
284                        } else if item_bottom > scroll_top + list_height - padding.bottom {
285                            updated_scroll_offset.y = -(item_bottom - list_height) - padding.bottom;
286                        }
287                        scroll_offset = *updated_scroll_offset;
288                    }
289
290                    let first_visible_element_ix =
291                        (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
292                    let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
293                        / item_height)
294                        .ceil() as usize;
295                    let visible_range = first_visible_element_ix
296                        ..cmp::min(last_visible_element_ix, self.item_count);
297
298                    let mut items = (self.render_items)(visible_range.clone(), cx);
299
300                    let content_mask = ContentMask { bounds };
301                    cx.with_content_mask(Some(content_mask), |cx| {
302                        for (mut item, ix) in items.into_iter().zip(visible_range.clone()) {
303                            let item_origin = padded_bounds.origin
304                                + point(
305                                    if can_scroll_horizontally {
306                                        scroll_offset.x + padding.left
307                                    } else {
308                                        scroll_offset.x
309                                    },
310                                    item_height * ix + scroll_offset.y + padding.top,
311                                );
312                            let available_width = if can_scroll_horizontally {
313                                padded_bounds.size.width + scroll_offset.x.abs()
314                            } else {
315                                padded_bounds.size.width
316                            };
317                            let available_space = size(
318                                AvailableSpace::Definite(available_width),
319                                AvailableSpace::Definite(item_height),
320                            );
321                            item.layout_as_root(available_space, cx);
322                            item.prepaint_at(item_origin, cx);
323                            frame_state.items.push(item);
324                        }
325
326                        let bounds = Bounds::new(
327                            padded_bounds.origin
328                                + point(
329                                    if can_scroll_horizontally {
330                                        scroll_offset.x + padding.left
331                                    } else {
332                                        scroll_offset.x
333                                    },
334                                    scroll_offset.y + padding.top,
335                                ),
336                            padded_bounds.size,
337                        );
338                        for decoration in &self.decorations {
339                            let mut decoration = decoration.as_ref().compute(
340                                visible_range.clone(),
341                                bounds,
342                                item_height,
343                                self.item_count,
344                                cx,
345                            );
346                            let available_space = size(
347                                AvailableSpace::Definite(bounds.size.width),
348                                AvailableSpace::Definite(bounds.size.height),
349                            );
350                            decoration.layout_as_root(available_space, cx);
351                            decoration.prepaint_at(bounds.origin, cx);
352                            frame_state.decorations.push(decoration);
353                        }
354                    });
355                }
356
357                hitbox
358            },
359        )
360    }
361
362    fn paint(
363        &mut self,
364        global_id: Option<&GlobalElementId>,
365        bounds: Bounds<crate::Pixels>,
366        request_layout: &mut Self::RequestLayoutState,
367        hitbox: &mut Option<Hitbox>,
368        cx: &mut WindowContext,
369    ) {
370        self.interactivity
371            .paint(global_id, bounds, hitbox.as_ref(), cx, |_, cx| {
372                for item in &mut request_layout.items {
373                    item.paint(cx);
374                }
375                for decoration in &mut request_layout.decorations {
376                    decoration.paint(cx);
377                }
378            })
379    }
380}
381
382impl IntoElement for UniformList {
383    type Element = Self;
384
385    fn into_element(self) -> Self::Element {
386        self
387    }
388}
389
390/// A decoration for a [`UniformList`]. This can be used for various things,
391/// such as rendering indent guides, or other visual effects.
392pub trait UniformListDecoration {
393    /// Compute the decoration element, given the visible range of list items,
394    /// the bounds of the list, and the height of each item.
395    fn compute(
396        &self,
397        visible_range: Range<usize>,
398        bounds: Bounds<Pixels>,
399        item_height: Pixels,
400        item_count: usize,
401        cx: &mut WindowContext,
402    ) -> AnyElement;
403}
404
405impl UniformList {
406    /// Selects a specific list item for measurement.
407    pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
408        self.item_to_measure_index = item_index.unwrap_or(0);
409        self
410    }
411
412    /// Sets the sizing behavior, similar to the `List` element.
413    pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
414        self.sizing_behavior = behavior;
415        self
416    }
417
418    /// Sets the horizontal sizing behavior, controlling the way list items laid out horizontally.
419    /// With [`ListHorizontalSizingBehavior::Unconstrained`] behavior, every item and the list itself will
420    /// have the size of the widest item and lay out pushing the `end_slot` to the right end.
421    pub fn with_horizontal_sizing_behavior(
422        mut self,
423        behavior: ListHorizontalSizingBehavior,
424    ) -> Self {
425        self.horizontal_sizing_behavior = behavior;
426        match behavior {
427            ListHorizontalSizingBehavior::FitList => {
428                self.interactivity.base_style.overflow.x = None;
429            }
430            ListHorizontalSizingBehavior::Unconstrained => {
431                self.interactivity.base_style.overflow.x = Some(Overflow::Scroll);
432            }
433        }
434        self
435    }
436
437    /// Adds a decoration element to the list.
438    pub fn with_decoration(mut self, decoration: impl UniformListDecoration + 'static) -> Self {
439        self.decorations.push(Box::new(decoration));
440        self
441    }
442
443    fn measure_item(&self, list_width: Option<Pixels>, cx: &mut WindowContext) -> Size<Pixels> {
444        if self.item_count == 0 {
445            return Size::default();
446        }
447
448        let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
449        let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
450        let Some(mut item_to_measure) = items.pop() else {
451            return Size::default();
452        };
453        let available_space = size(
454            list_width.map_or(AvailableSpace::MinContent, |width| {
455                AvailableSpace::Definite(width)
456            }),
457            AvailableSpace::MinContent,
458        );
459        item_to_measure.layout_as_root(available_space, cx)
460    }
461
462    /// Track and render scroll state of this list with reference to the given scroll handle.
463    pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
464        self.interactivity.tracked_scroll_handle = Some(handle.0.borrow().base_handle.clone());
465        self.scroll_handle = Some(handle);
466        self
467    }
468}
469
470impl InteractiveElement for UniformList {
471    fn interactivity(&mut self) -> &mut crate::Interactivity {
472        &mut self.interactivity
473    }
474}