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, Debug, Default)]
83pub struct UniformListScrollHandle(pub Rc<RefCell<UniformListScrollState>>);
84
85#[derive(Clone, Debug, Default)]
86#[allow(missing_docs)]
87pub struct UniformListScrollState {
88 pub base_handle: ScrollHandle,
89 pub deferred_scroll_to_item: Option<usize>,
90 pub last_item_height: Option<Pixels>,
91}
92
93impl UniformListScrollHandle {
94 /// Create a new scroll handle to bind to a uniform list.
95 pub fn new() -> Self {
96 Self(Rc::new(RefCell::new(UniformListScrollState {
97 base_handle: ScrollHandle::new(),
98 deferred_scroll_to_item: None,
99 last_item_height: None,
100 })))
101 }
102
103 /// Scroll the list to the given item index.
104 pub fn scroll_to_item(&mut self, ix: usize) {
105 self.0.borrow_mut().deferred_scroll_to_item = Some(ix);
106 }
107
108 /// Get the index of the topmost visible child.
109 pub fn logical_scroll_top_index(&self) -> usize {
110 let this = self.0.borrow();
111 this.deferred_scroll_to_item
112 .unwrap_or_else(|| this.base_handle.logical_scroll_top().0)
113 }
114}
115
116impl Styled for UniformList {
117 fn style(&mut self) -> &mut StyleRefinement {
118 &mut self.interactivity.base_style
119 }
120}
121
122impl Element for UniformList {
123 type RequestLayoutState = UniformListFrameState;
124 type PrepaintState = Option<Hitbox>;
125
126 fn id(&self) -> Option<ElementId> {
127 self.interactivity.element_id.clone()
128 }
129
130 fn request_layout(
131 &mut self,
132 global_id: Option<&GlobalElementId>,
133 cx: &mut WindowContext,
134 ) -> (LayoutId, Self::RequestLayoutState) {
135 let max_items = self.item_count;
136 let item_size = self.measure_item(None, cx);
137 let layout_id = self
138 .interactivity
139 .request_layout(global_id, cx, |style, cx| match self.sizing_behavior {
140 ListSizingBehavior::Infer => {
141 cx.with_text_style(style.text_style().cloned(), |cx| {
142 cx.request_measured_layout(
143 style,
144 move |known_dimensions, available_space, _cx| {
145 let desired_height = item_size.height * max_items;
146 let width = known_dimensions.width.unwrap_or(match available_space
147 .width
148 {
149 AvailableSpace::Definite(x) => x,
150 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
151 item_size.width
152 }
153 });
154 let height = match available_space.height {
155 AvailableSpace::Definite(height) => desired_height.min(height),
156 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
157 desired_height
158 }
159 };
160 size(width, height)
161 },
162 )
163 })
164 }
165 ListSizingBehavior::Auto => cx.with_text_style(style.text_style().cloned(), |cx| {
166 cx.request_layout(style, None)
167 }),
168 });
169
170 (
171 layout_id,
172 UniformListFrameState {
173 item_size,
174 items: SmallVec::new(),
175 },
176 )
177 }
178
179 fn prepaint(
180 &mut self,
181 global_id: Option<&GlobalElementId>,
182 bounds: Bounds<Pixels>,
183 frame_state: &mut Self::RequestLayoutState,
184 cx: &mut WindowContext,
185 ) -> Option<Hitbox> {
186 let style = self.interactivity.compute_style(global_id, None, cx);
187 let border = style.border_widths.to_pixels(cx.rem_size());
188 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
189
190 let padded_bounds = Bounds::from_corners(
191 bounds.origin + point(border.left + padding.left, border.top + padding.top),
192 bounds.lower_right()
193 - point(border.right + padding.right, border.bottom + padding.bottom),
194 );
195
196 let content_size = Size {
197 width: padded_bounds.size.width,
198 height: frame_state.item_size.height * self.item_count + padding.top + padding.bottom,
199 };
200
201 let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
202
203 let item_height = self.measure_item(Some(padded_bounds.size.width), cx).height;
204 let shared_scroll_to_item = self.scroll_handle.as_mut().and_then(|handle| {
205 let mut handle = handle.0.borrow_mut();
206 handle.last_item_height = Some(item_height);
207 handle.deferred_scroll_to_item.take()
208 });
209
210 self.interactivity.prepaint(
211 global_id,
212 bounds,
213 content_size,
214 cx,
215 |style, mut scroll_offset, hitbox, cx| {
216 let border = style.border_widths.to_pixels(cx.rem_size());
217 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
218
219 let padded_bounds = Bounds::from_corners(
220 bounds.origin + point(border.left + padding.left, border.top),
221 bounds.lower_right() - point(border.right + padding.right, border.bottom),
222 );
223
224 if let Some(handle) = self.scroll_handle.as_mut() {
225 handle.0.borrow_mut().base_handle.set_bounds(bounds);
226 }
227
228 if self.item_count > 0 {
229 let content_height =
230 item_height * self.item_count + padding.top + padding.bottom;
231 let min_scroll_offset = padded_bounds.size.height - content_height;
232 let is_scrolled = scroll_offset.y != px(0.);
233
234 if is_scrolled && scroll_offset.y < min_scroll_offset {
235 shared_scroll_offset.borrow_mut().y = min_scroll_offset;
236 scroll_offset.y = min_scroll_offset;
237 }
238
239 if let Some(ix) = shared_scroll_to_item {
240 let list_height = padded_bounds.size.height;
241 let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
242 let item_top = item_height * ix + padding.top;
243 let item_bottom = item_top + item_height;
244 let scroll_top = -updated_scroll_offset.y;
245 if item_top < scroll_top + padding.top {
246 updated_scroll_offset.y = -(item_top) + padding.top;
247 } else if item_bottom > scroll_top + list_height - padding.bottom {
248 updated_scroll_offset.y = -(item_bottom - list_height) - padding.bottom;
249 }
250 scroll_offset = *updated_scroll_offset;
251 }
252
253 let first_visible_element_ix =
254 (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
255 let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
256 / item_height)
257 .ceil() as usize;
258 let visible_range = first_visible_element_ix
259 ..cmp::min(last_visible_element_ix, self.item_count);
260
261 let mut items = (self.render_items)(visible_range.clone(), cx);
262 let content_mask = ContentMask { bounds };
263 cx.with_content_mask(Some(content_mask), |cx| {
264 for (mut item, ix) in items.into_iter().zip(visible_range) {
265 let item_origin = padded_bounds.origin
266 + point(px(0.), item_height * ix + scroll_offset.y + padding.top);
267 let available_space = size(
268 AvailableSpace::Definite(padded_bounds.size.width),
269 AvailableSpace::Definite(item_height),
270 );
271 item.layout_as_root(available_space, cx);
272 item.prepaint_at(item_origin, cx);
273 frame_state.items.push(item);
274 }
275 });
276 }
277
278 hitbox
279 },
280 )
281 }
282
283 fn paint(
284 &mut self,
285 global_id: Option<&GlobalElementId>,
286 bounds: Bounds<crate::Pixels>,
287 request_layout: &mut Self::RequestLayoutState,
288 hitbox: &mut Option<Hitbox>,
289 cx: &mut WindowContext,
290 ) {
291 self.interactivity
292 .paint(global_id, bounds, hitbox.as_ref(), cx, |_, cx| {
293 for item in &mut request_layout.items {
294 item.paint(cx);
295 }
296 })
297 }
298}
299
300impl IntoElement for UniformList {
301 type Element = Self;
302
303 fn into_element(self) -> Self::Element {
304 self
305 }
306}
307
308impl UniformList {
309 /// Selects a specific list item for measurement.
310 pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
311 self.item_to_measure_index = item_index.unwrap_or(0);
312 self
313 }
314
315 /// Sets the sizing behavior, similar to the `List` element.
316 pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
317 self.sizing_behavior = behavior;
318 self
319 }
320
321 fn measure_item(&self, list_width: Option<Pixels>, cx: &mut WindowContext) -> Size<Pixels> {
322 if self.item_count == 0 {
323 return Size::default();
324 }
325
326 let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
327 let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
328 let mut item_to_measure = items.pop().unwrap();
329 let available_space = size(
330 list_width.map_or(AvailableSpace::MinContent, |width| {
331 AvailableSpace::Definite(width)
332 }),
333 AvailableSpace::MinContent,
334 );
335 item_to_measure.layout_as_root(available_space, cx)
336 }
337
338 /// Track and render scroll state of this list with reference to the given scroll handle.
339 pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
340 self.interactivity.tracked_scroll_handle = Some(handle.0.borrow().base_handle.clone());
341 self.scroll_handle = Some(handle);
342 self
343 }
344}
345
346impl InteractiveElement for UniformList {
347 fn interactivity(&mut self) -> &mut crate::Interactivity {
348 &mut self.interactivity
349 }
350}