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