uniform_list.rs

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