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, px, size, AnyElement, AvailableSpace, Bounds, ContentMask, Element, ElementId,
  9    GlobalElementId, Hitbox, InteractiveElement, Interactivity, IntoElement, 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
 17/// uniform_list provides lazy rendering for a set of items that are of uniform height.
 18/// When rendered into a container with overflow-y: hidden and a fixed (or max) height,
 19/// uniform_list will only render the visible subset of items.
 20#[track_caller]
 21pub fn uniform_list<I, R, V>(
 22    view: View<V>,
 23    id: I,
 24    item_count: usize,
 25    f: impl 'static + Fn(&mut V, Range<usize>, &mut ViewContext<V>) -> Vec<R>,
 26) -> UniformList
 27where
 28    I: Into<ElementId>,
 29    R: IntoElement,
 30    V: Render,
 31{
 32    let id = id.into();
 33    let mut base_style = StyleRefinement::default();
 34    base_style.overflow.y = Some(Overflow::Scroll);
 35
 36    let render_range = move |range, cx: &mut WindowContext| {
 37        view.update(cx, |this, cx| {
 38            f(this, range, cx)
 39                .into_iter()
 40                .map(|component| component.into_any_element())
 41                .collect()
 42        })
 43    };
 44
 45    UniformList {
 46        item_count,
 47        item_to_measure_index: 0,
 48        render_items: Box::new(render_range),
 49        interactivity: Interactivity {
 50            element_id: Some(id),
 51            base_style: Box::new(base_style),
 52
 53            #[cfg(debug_assertions)]
 54            location: Some(*core::panic::Location::caller()),
 55
 56            ..Default::default()
 57        },
 58        scroll_handle: None,
 59        sizing_behavior: ListSizingBehavior::default(),
 60    }
 61}
 62
 63/// A list element for efficiently laying out and displaying a list of uniform-height elements.
 64pub struct UniformList {
 65    item_count: usize,
 66    item_to_measure_index: usize,
 67    render_items:
 68        Box<dyn for<'a> Fn(Range<usize>, &'a mut WindowContext) -> SmallVec<[AnyElement; 64]>>,
 69    interactivity: Interactivity,
 70    scroll_handle: Option<UniformListScrollHandle>,
 71    sizing_behavior: ListSizingBehavior,
 72}
 73
 74/// Frame state used by the [UniformList].
 75pub struct UniformListFrameState {
 76    item_size: Size<Pixels>,
 77    items: SmallVec<[AnyElement; 32]>,
 78}
 79
 80/// A handle for controlling the scroll position of a uniform list.
 81/// This should be stored in your view and passed to the uniform_list on each frame.
 82#[derive(Clone, Default)]
 83pub struct UniformListScrollHandle {
 84    base_handle: ScrollHandle,
 85    deferred_scroll_to_item: Rc<RefCell<Option<usize>>>,
 86}
 87
 88impl UniformListScrollHandle {
 89    /// Create a new scroll handle to bind to a uniform list.
 90    pub fn new() -> Self {
 91        Self {
 92            base_handle: ScrollHandle::new(),
 93            deferred_scroll_to_item: Rc::new(RefCell::new(None)),
 94        }
 95    }
 96
 97    /// Scroll the list to the given item index.
 98    pub fn scroll_to_item(&mut self, ix: usize) {
 99        self.deferred_scroll_to_item.replace(Some(ix));
100    }
101
102    /// Get the index of the topmost visible child.
103    pub fn logical_scroll_top_index(&self) -> usize {
104        self.deferred_scroll_to_item
105            .borrow()
106            .unwrap_or_else(|| self.base_handle.logical_scroll_top().0)
107    }
108}
109
110impl Styled for UniformList {
111    fn style(&mut self) -> &mut StyleRefinement {
112        &mut self.interactivity.base_style
113    }
114}
115
116impl Element for UniformList {
117    type RequestLayoutState = UniformListFrameState;
118    type PrepaintState = Option<Hitbox>;
119
120    fn id(&self) -> Option<ElementId> {
121        self.interactivity.element_id.clone()
122    }
123
124    fn request_layout(
125        &mut self,
126        global_id: Option<&GlobalElementId>,
127        cx: &mut WindowContext,
128    ) -> (LayoutId, Self::RequestLayoutState) {
129        let max_items = self.item_count;
130        let item_size = self.measure_item(None, cx);
131        let layout_id = self
132            .interactivity
133            .request_layout(global_id, cx, |style, cx| match self.sizing_behavior {
134                ListSizingBehavior::Infer => {
135                    cx.with_text_style(style.text_style().cloned(), |cx| {
136                        cx.request_measured_layout(
137                            style,
138                            move |known_dimensions, available_space, _cx| {
139                                let desired_height = item_size.height * max_items;
140                                let width = known_dimensions.width.unwrap_or(match available_space
141                                    .width
142                                {
143                                    AvailableSpace::Definite(x) => x,
144                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
145                                        item_size.width
146                                    }
147                                });
148                                let height = match available_space.height {
149                                    AvailableSpace::Definite(height) => desired_height.min(height),
150                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
151                                        desired_height
152                                    }
153                                };
154                                size(width, height)
155                            },
156                        )
157                    })
158                }
159                ListSizingBehavior::Auto => cx.with_text_style(style.text_style().cloned(), |cx| {
160                    cx.request_layout(style, None)
161                }),
162            });
163
164        (
165            layout_id,
166            UniformListFrameState {
167                item_size,
168                items: SmallVec::new(),
169            },
170        )
171    }
172
173    fn prepaint(
174        &mut self,
175        global_id: Option<&GlobalElementId>,
176        bounds: Bounds<Pixels>,
177        frame_state: &mut Self::RequestLayoutState,
178        cx: &mut WindowContext,
179    ) -> Option<Hitbox> {
180        let style = self.interactivity.compute_style(global_id, None, cx);
181        let border = style.border_widths.to_pixels(cx.rem_size());
182        let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
183
184        let padded_bounds = Bounds::from_corners(
185            bounds.origin + point(border.left + padding.left, border.top + padding.top),
186            bounds.lower_right()
187                - point(border.right + padding.right, border.bottom + padding.bottom),
188        );
189
190        let content_size = Size {
191            width: padded_bounds.size.width,
192            height: frame_state.item_size.height * self.item_count + padding.top + padding.bottom,
193        };
194
195        let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
196
197        let item_height = self.measure_item(Some(padded_bounds.size.width), cx).height;
198        let shared_scroll_to_item = self
199            .scroll_handle
200            .as_mut()
201            .and_then(|handle| handle.deferred_scroll_to_item.take());
202
203        self.interactivity.prepaint(
204            global_id,
205            bounds,
206            content_size,
207            cx,
208            |style, mut scroll_offset, hitbox, cx| {
209                let border = style.border_widths.to_pixels(cx.rem_size());
210                let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
211
212                let padded_bounds = Bounds::from_corners(
213                    bounds.origin + point(border.left + padding.left, border.top),
214                    bounds.lower_right() - point(border.right + padding.right, border.bottom),
215                );
216
217                if self.item_count > 0 {
218                    let content_height =
219                        item_height * self.item_count + padding.top + padding.bottom;
220                    let min_scroll_offset = padded_bounds.size.height - content_height;
221                    let is_scrolled = scroll_offset.y != px(0.);
222
223                    if is_scrolled && scroll_offset.y < min_scroll_offset {
224                        shared_scroll_offset.borrow_mut().y = min_scroll_offset;
225                        scroll_offset.y = min_scroll_offset;
226                    }
227
228                    if let Some(ix) = shared_scroll_to_item {
229                        let list_height = padded_bounds.size.height;
230                        let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
231                        let item_top = item_height * ix + padding.top;
232                        let item_bottom = item_top + item_height;
233                        let scroll_top = -updated_scroll_offset.y;
234                        if item_top < scroll_top + padding.top {
235                            updated_scroll_offset.y = -(item_top) + padding.top;
236                        } else if item_bottom > scroll_top + list_height - padding.bottom {
237                            updated_scroll_offset.y = -(item_bottom - list_height) - padding.bottom;
238                        }
239                        scroll_offset = *updated_scroll_offset;
240                    }
241
242                    let first_visible_element_ix =
243                        (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
244                    let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
245                        / item_height)
246                        .ceil() as usize;
247                    let visible_range = first_visible_element_ix
248                        ..cmp::min(last_visible_element_ix, self.item_count);
249
250                    let mut items = (self.render_items)(visible_range.clone(), cx);
251                    let content_mask = ContentMask { bounds };
252                    cx.with_content_mask(Some(content_mask), |cx| {
253                        for (mut item, ix) in items.into_iter().zip(visible_range) {
254                            let item_origin = padded_bounds.origin
255                                + point(px(0.), item_height * ix + scroll_offset.y + padding.top);
256                            let available_space = size(
257                                AvailableSpace::Definite(padded_bounds.size.width),
258                                AvailableSpace::Definite(item_height),
259                            );
260                            item.layout_as_root(available_space, cx);
261                            item.prepaint_at(item_origin, cx);
262                            frame_state.items.push(item);
263                        }
264                    });
265                }
266
267                hitbox
268            },
269        )
270    }
271
272    fn paint(
273        &mut self,
274        global_id: Option<&GlobalElementId>,
275        bounds: Bounds<crate::Pixels>,
276        request_layout: &mut Self::RequestLayoutState,
277        hitbox: &mut Option<Hitbox>,
278        cx: &mut WindowContext,
279    ) {
280        self.interactivity
281            .paint(global_id, bounds, hitbox.as_ref(), cx, |_, cx| {
282                for item in &mut request_layout.items {
283                    item.paint(cx);
284                }
285            })
286    }
287}
288
289impl IntoElement for UniformList {
290    type Element = Self;
291
292    fn into_element(self) -> Self::Element {
293        self
294    }
295}
296
297impl UniformList {
298    /// Selects a specific list item for measurement.
299    pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
300        self.item_to_measure_index = item_index.unwrap_or(0);
301        self
302    }
303
304    /// Sets the sizing behavior, similar to the `List` element.
305    pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
306        self.sizing_behavior = behavior;
307        self
308    }
309
310    fn measure_item(&self, list_width: Option<Pixels>, cx: &mut WindowContext) -> Size<Pixels> {
311        if self.item_count == 0 {
312            return Size::default();
313        }
314
315        let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
316        let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
317        let mut item_to_measure = items.pop().unwrap();
318        let available_space = size(
319            list_width.map_or(AvailableSpace::MinContent, |width| {
320                AvailableSpace::Definite(width)
321            }),
322            AvailableSpace::MinContent,
323        );
324        item_to_measure.layout_as_root(available_space, cx)
325    }
326
327    /// Track and render scroll state of this list with reference to the given scroll handle.
328    pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
329        self.interactivity.tracked_scroll_handle = Some(handle.base_handle.clone());
330        self.scroll_handle = Some(handle);
331        self
332    }
333}
334
335impl InteractiveElement for UniformList {
336    fn interactivity(&mut self) -> &mut crate::Interactivity {
337        &mut self.interactivity
338    }
339}