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