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, ElementContext,
  9    ElementId, Hitbox, InteractiveElement, Interactivity, IntoElement, LayoutId, Pixels, Render,
 10    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 request_layout(&mut self, cx: &mut ElementContext) -> (LayoutId, Self::RequestLayoutState) {
111        let max_items = self.item_count;
112        let item_size = self.measure_item(None, cx);
113        let layout_id = self.interactivity.request_layout(cx, |style, cx| {
114            cx.request_measured_layout(style, move |known_dimensions, available_space, _cx| {
115                let desired_height = item_size.height * max_items;
116                let width = known_dimensions
117                    .width
118                    .unwrap_or(match available_space.width {
119                        AvailableSpace::Definite(x) => x,
120                        AvailableSpace::MinContent | AvailableSpace::MaxContent => item_size.width,
121                    });
122
123                let height = match available_space.height {
124                    AvailableSpace::Definite(height) => desired_height.min(height),
125                    AvailableSpace::MinContent | AvailableSpace::MaxContent => desired_height,
126                };
127                size(width, height)
128            })
129        });
130
131        (
132            layout_id,
133            UniformListFrameState {
134                item_size,
135                items: SmallVec::new(),
136            },
137        )
138    }
139
140    fn prepaint(
141        &mut self,
142        bounds: Bounds<Pixels>,
143        frame_state: &mut Self::RequestLayoutState,
144        cx: &mut ElementContext,
145    ) -> Option<Hitbox> {
146        let style = self.interactivity.compute_style(None, cx);
147        let border = style.border_widths.to_pixels(cx.rem_size());
148        let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
149
150        let padded_bounds = Bounds::from_corners(
151            bounds.origin + point(border.left + padding.left, border.top + padding.top),
152            bounds.lower_right()
153                - point(border.right + padding.right, border.bottom + padding.bottom),
154        );
155
156        let content_size = Size {
157            width: padded_bounds.size.width,
158            height: frame_state.item_size.height * self.item_count + padding.top + padding.bottom,
159        };
160
161        let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
162
163        let item_height = self.measure_item(Some(padded_bounds.size.width), cx).height;
164        let shared_scroll_to_item = self
165            .scroll_handle
166            .as_mut()
167            .and_then(|handle| handle.deferred_scroll_to_item.take());
168
169        self.interactivity.prepaint(
170            bounds,
171            content_size,
172            cx,
173            |style, mut scroll_offset, hitbox, cx| {
174                let border = style.border_widths.to_pixels(cx.rem_size());
175                let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
176
177                let padded_bounds = Bounds::from_corners(
178                    bounds.origin + point(border.left + padding.left, border.top),
179                    bounds.lower_right() - point(border.right + padding.right, border.bottom),
180                );
181
182                if self.item_count > 0 {
183                    let content_height =
184                        item_height * self.item_count + padding.top + padding.bottom;
185                    let min_scroll_offset = padded_bounds.size.height - content_height;
186                    let is_scrolled = scroll_offset.y != px(0.);
187
188                    if is_scrolled && scroll_offset.y < min_scroll_offset {
189                        shared_scroll_offset.borrow_mut().y = min_scroll_offset;
190                        scroll_offset.y = min_scroll_offset;
191                    }
192
193                    if let Some(ix) = shared_scroll_to_item {
194                        let list_height = padded_bounds.size.height;
195                        let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
196                        let item_top = item_height * ix + padding.top;
197                        let item_bottom = item_top + item_height;
198                        let scroll_top = -updated_scroll_offset.y;
199                        if item_top < scroll_top + padding.top {
200                            updated_scroll_offset.y = -(item_top) + padding.top;
201                        } else if item_bottom > scroll_top + list_height - padding.bottom {
202                            updated_scroll_offset.y = -(item_bottom - list_height) - padding.bottom;
203                        }
204                        scroll_offset = *updated_scroll_offset;
205                    }
206
207                    let first_visible_element_ix =
208                        (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
209                    let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
210                        / item_height)
211                        .ceil() as usize;
212                    let visible_range = first_visible_element_ix
213                        ..cmp::min(last_visible_element_ix, self.item_count);
214
215                    let mut items = (self.render_items)(visible_range.clone(), cx);
216                    let content_mask = ContentMask { bounds };
217                    cx.with_content_mask(Some(content_mask), |cx| {
218                        for (mut item, ix) in items.into_iter().zip(visible_range) {
219                            let item_origin = padded_bounds.origin
220                                + point(px(0.), item_height * ix + scroll_offset.y + padding.top);
221                            let available_space = size(
222                                AvailableSpace::Definite(padded_bounds.size.width),
223                                AvailableSpace::Definite(item_height),
224                            );
225                            item.layout_as_root(available_space, cx);
226                            item.prepaint_at(item_origin, cx);
227                            frame_state.items.push(item);
228                        }
229                    });
230                }
231
232                hitbox
233            },
234        )
235    }
236
237    fn paint(
238        &mut self,
239        bounds: Bounds<crate::Pixels>,
240        request_layout: &mut Self::RequestLayoutState,
241        hitbox: &mut Option<Hitbox>,
242        cx: &mut ElementContext,
243    ) {
244        self.interactivity
245            .paint(bounds, hitbox.as_ref(), cx, |_, cx| {
246                for item in &mut request_layout.items {
247                    item.paint(cx);
248                }
249            })
250    }
251}
252
253impl IntoElement for UniformList {
254    type Element = Self;
255
256    fn into_element(self) -> Self::Element {
257        self
258    }
259}
260
261impl UniformList {
262    /// Selects a specific list item for measurement.
263    pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
264        self.item_to_measure_index = item_index.unwrap_or(0);
265        self
266    }
267
268    fn measure_item(&self, list_width: Option<Pixels>, cx: &mut ElementContext) -> Size<Pixels> {
269        if self.item_count == 0 {
270            return Size::default();
271        }
272
273        let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
274        let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
275        let mut item_to_measure = items.pop().unwrap();
276        let available_space = size(
277            list_width.map_or(AvailableSpace::MinContent, |width| {
278                AvailableSpace::Definite(width)
279            }),
280            AvailableSpace::MinContent,
281        );
282        item_to_measure.layout_as_root(available_space, cx)
283    }
284
285    /// Track and render scroll state of this list with reference to the given scroll handle.
286    pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
287        self.interactivity.tracked_scroll_handle = Some(handle.base_handle.clone());
288        self.scroll_handle = Some(handle);
289        self
290    }
291}
292
293impl InteractiveElement for UniformList {
294    fn interactivity(&mut self) -> &mut crate::Interactivity {
295        &mut self.interactivity
296    }
297}