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            occlude_mouse: true,
 52
 53            #[cfg(debug_assertions)]
 54            location: Some(*core::panic::Location::caller()),
 55
 56            ..Default::default()
 57        },
 58        scroll_handle: None,
 59    }
 60}
 61
 62/// A list element for efficiently laying out and displaying a list of uniform-height elements.
 63pub struct UniformList {
 64    item_count: usize,
 65    item_to_measure_index: usize,
 66    render_items:
 67        Box<dyn for<'a> Fn(Range<usize>, &'a mut WindowContext) -> SmallVec<[AnyElement; 64]>>,
 68    interactivity: Interactivity,
 69    scroll_handle: Option<UniformListScrollHandle>,
 70}
 71
 72/// Frame state used by the [UniformList].
 73pub struct UniformListFrameState {
 74    item_size: Size<Pixels>,
 75    items: SmallVec<[AnyElement; 32]>,
 76}
 77
 78/// A handle for controlling the scroll position of a uniform list.
 79/// This should be stored in your view and passed to the uniform_list on each frame.
 80#[derive(Clone, Default)]
 81pub struct UniformListScrollHandle {
 82    base_handle: ScrollHandle,
 83    deferred_scroll_to_item: Rc<RefCell<Option<usize>>>,
 84}
 85
 86impl UniformListScrollHandle {
 87    /// Create a new scroll handle to bind to a uniform list.
 88    pub fn new() -> Self {
 89        Self {
 90            base_handle: ScrollHandle::new(),
 91            deferred_scroll_to_item: Rc::new(RefCell::new(None)),
 92        }
 93    }
 94
 95    /// Scroll the list to the given item index.
 96    pub fn scroll_to_item(&mut self, ix: usize) {
 97        self.deferred_scroll_to_item.replace(Some(ix));
 98    }
 99}
100
101impl Styled for UniformList {
102    fn style(&mut self) -> &mut StyleRefinement {
103        &mut self.interactivity.base_style
104    }
105}
106
107impl Element for UniformList {
108    type BeforeLayout = UniformListFrameState;
109    type AfterLayout = Option<Hitbox>;
110
111    fn before_layout(&mut self, cx: &mut ElementContext) -> (LayoutId, Self::BeforeLayout) {
112        let max_items = self.item_count;
113        let item_size = self.measure_item(None, cx);
114        let layout_id = self.interactivity.before_layout(cx, |style, cx| {
115            cx.request_measured_layout(style, move |known_dimensions, available_space, _cx| {
116                let desired_height = item_size.height * max_items;
117                let width = known_dimensions
118                    .width
119                    .unwrap_or(match available_space.width {
120                        AvailableSpace::Definite(x) => x,
121                        AvailableSpace::MinContent | AvailableSpace::MaxContent => item_size.width,
122                    });
123
124                let height = match available_space.height {
125                    AvailableSpace::Definite(height) => desired_height.min(height),
126                    AvailableSpace::MinContent | AvailableSpace::MaxContent => desired_height,
127                };
128                size(width, height)
129            })
130        });
131
132        (
133            layout_id,
134            UniformListFrameState {
135                item_size,
136                items: SmallVec::new(),
137            },
138        )
139    }
140
141    fn after_layout(
142        &mut self,
143        bounds: Bounds<Pixels>,
144        before_layout: &mut Self::BeforeLayout,
145        cx: &mut ElementContext,
146    ) -> Option<Hitbox> {
147        let style = self.interactivity.compute_style(None, cx);
148        let border = style.border_widths.to_pixels(cx.rem_size());
149        let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
150
151        let padded_bounds = Bounds::from_corners(
152            bounds.origin + point(border.left + padding.left, border.top + padding.top),
153            bounds.lower_right()
154                - point(border.right + padding.right, border.bottom + padding.bottom),
155        );
156
157        let content_size = Size {
158            width: padded_bounds.size.width,
159            height: before_layout.item_size.height * self.item_count + padding.top + padding.bottom,
160        };
161
162        let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
163
164        let item_height = self.measure_item(Some(padded_bounds.size.width), cx).height;
165        let shared_scroll_to_item = self
166            .scroll_handle
167            .as_mut()
168            .and_then(|handle| handle.deferred_scroll_to_item.take());
169
170        self.interactivity.after_layout(
171            bounds,
172            content_size,
173            cx,
174            |style, mut scroll_offset, hitbox, cx| {
175                let border = style.border_widths.to_pixels(cx.rem_size());
176                let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
177
178                let padded_bounds = Bounds::from_corners(
179                    bounds.origin + point(border.left + padding.left, border.top),
180                    bounds.lower_right() - point(border.right + padding.right, border.bottom),
181                );
182
183                if self.item_count > 0 {
184                    let content_height =
185                        item_height * self.item_count + padding.top + padding.bottom;
186                    let min_scroll_offset = padded_bounds.size.height - content_height;
187                    let is_scrolled = scroll_offset.y != px(0.);
188
189                    if is_scrolled && scroll_offset.y < min_scroll_offset {
190                        shared_scroll_offset.borrow_mut().y = min_scroll_offset;
191                        scroll_offset.y = min_scroll_offset;
192                    }
193
194                    if let Some(ix) = shared_scroll_to_item {
195                        let list_height = padded_bounds.size.height;
196                        let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
197                        let item_top = item_height * ix + padding.top;
198                        let item_bottom = item_top + item_height;
199                        let scroll_top = -updated_scroll_offset.y;
200                        if item_top < scroll_top + padding.top {
201                            updated_scroll_offset.y = -(item_top) + padding.top;
202                        } else if item_bottom > scroll_top + list_height - padding.bottom {
203                            updated_scroll_offset.y = -(item_bottom - list_height) - padding.bottom;
204                        }
205                        scroll_offset = *updated_scroll_offset;
206                    }
207
208                    let first_visible_element_ix =
209                        (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
210                    let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
211                        / item_height)
212                        .ceil() as usize;
213                    let visible_range = first_visible_element_ix
214                        ..cmp::min(last_visible_element_ix, self.item_count);
215
216                    let mut items = (self.render_items)(visible_range.clone(), cx);
217                    let content_mask = ContentMask { bounds };
218                    cx.with_content_mask(Some(content_mask), |cx| {
219                        for (mut item, ix) in items.into_iter().zip(visible_range) {
220                            let item_origin = padded_bounds.origin
221                                + point(px(0.), item_height * ix + scroll_offset.y + padding.top);
222                            let available_space = size(
223                                AvailableSpace::Definite(padded_bounds.size.width),
224                                AvailableSpace::Definite(item_height),
225                            );
226                            item.layout(item_origin, available_space, cx);
227                            before_layout.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        before_layout: &mut Self::BeforeLayout,
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 before_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.measure(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}