uniform_list.rs

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