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, InteractiveElement, InteractiveElementState, Interactivity, IntoElement, LayoutId,
10 Pixels, Render, 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 id: id.clone(),
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 }
60}
61
62/// A list element for efficiently laying out and displaying a list of uniform-height elements.
63pub struct UniformList {
64 id: ElementId,
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}
72
73/// A handle for controlling the scroll position of a uniform list.
74/// This should be stored in your view and passed to the uniform_list on each frame.
75#[derive(Clone, Default)]
76pub struct UniformListScrollHandle {
77 base_handle: ScrollHandle,
78 deferred_scroll_to_item: Rc<RefCell<Option<usize>>>,
79}
80
81impl UniformListScrollHandle {
82 /// Create a new scroll handle to bind to a uniform list.
83 pub fn new() -> Self {
84 Self {
85 base_handle: ScrollHandle::new(),
86 deferred_scroll_to_item: Rc::new(RefCell::new(None)),
87 }
88 }
89
90 /// Scroll the list to the given item index.
91 pub fn scroll_to_item(&mut self, ix: usize) {
92 self.deferred_scroll_to_item.replace(Some(ix));
93 }
94}
95
96impl Styled for UniformList {
97 fn style(&mut self) -> &mut StyleRefinement {
98 &mut self.interactivity.base_style
99 }
100}
101
102#[doc(hidden)]
103#[derive(Default)]
104pub struct UniformListState {
105 interactive: InteractiveElementState,
106 item_size: Size<Pixels>,
107}
108
109impl Element for UniformList {
110 type State = UniformListState;
111
112 fn request_layout(
113 &mut self,
114 state: Option<Self::State>,
115 cx: &mut ElementContext,
116 ) -> (LayoutId, Self::State) {
117 let max_items = self.item_count;
118 let item_size = state
119 .as_ref()
120 .map(|s| s.item_size)
121 .unwrap_or_else(|| self.measure_item(None, cx));
122
123 let (layout_id, interactive) =
124 self.interactivity
125 .layout(state.map(|s| s.interactive), cx, |style, cx| {
126 cx.request_measured_layout(
127 style,
128 move |known_dimensions, available_space, _cx| {
129 let desired_height = item_size.height * max_items;
130 let width =
131 known_dimensions
132 .width
133 .unwrap_or(match available_space.width {
134 AvailableSpace::Definite(x) => x,
135 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
136 item_size.width
137 }
138 });
139
140 let height = match available_space.height {
141 AvailableSpace::Definite(height) => desired_height.min(height),
142 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
143 desired_height
144 }
145 };
146 size(width, height)
147 },
148 )
149 });
150
151 let element_state = UniformListState {
152 interactive,
153 item_size,
154 };
155
156 (layout_id, element_state)
157 }
158
159 fn paint(
160 &mut self,
161 bounds: Bounds<crate::Pixels>,
162 element_state: &mut Self::State,
163 cx: &mut ElementContext,
164 ) {
165 let style =
166 self.interactivity
167 .compute_style(Some(bounds), &mut element_state.interactive, cx);
168 let border = style.border_widths.to_pixels(cx.rem_size());
169 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
170
171 let padded_bounds = Bounds::from_corners(
172 bounds.origin + point(border.left + padding.left, border.top + padding.top),
173 bounds.lower_right()
174 - point(border.right + padding.right, border.bottom + padding.bottom),
175 );
176
177 let item_size = element_state.item_size;
178 let content_size = Size {
179 width: padded_bounds.size.width,
180 height: item_size.height * self.item_count + padding.top + padding.bottom,
181 };
182
183 let shared_scroll_offset = element_state
184 .interactive
185 .scroll_offset
186 .get_or_insert_with(Rc::default)
187 .clone();
188
189 let item_height = self.measure_item(Some(padded_bounds.size.width), cx).height;
190 let shared_scroll_to_item = self
191 .scroll_handle
192 .as_mut()
193 .and_then(|handle| handle.deferred_scroll_to_item.take());
194
195 self.interactivity.paint(
196 bounds,
197 content_size,
198 &mut element_state.interactive,
199 cx,
200 |style, mut scroll_offset, cx| {
201 let border = style.border_widths.to_pixels(cx.rem_size());
202 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
203
204 let padded_bounds = Bounds::from_corners(
205 bounds.origin + point(border.left + padding.left, border.top),
206 bounds.lower_right() - point(border.right + padding.right, border.bottom),
207 );
208
209 if self.item_count > 0 {
210 let content_height =
211 item_height * self.item_count + padding.top + padding.bottom;
212 let min_scroll_offset = padded_bounds.size.height - content_height;
213 let is_scrolled = scroll_offset.y != px(0.);
214
215 if is_scrolled && scroll_offset.y < min_scroll_offset {
216 shared_scroll_offset.borrow_mut().y = min_scroll_offset;
217 scroll_offset.y = min_scroll_offset;
218 }
219
220 if let Some(ix) = shared_scroll_to_item {
221 let list_height = padded_bounds.size.height;
222 let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
223 let item_top = item_height * ix + padding.top;
224 let item_bottom = item_top + item_height;
225 let scroll_top = -updated_scroll_offset.y;
226 if item_top < scroll_top + padding.top {
227 updated_scroll_offset.y = -(item_top) + padding.top;
228 } else if item_bottom > scroll_top + list_height - padding.bottom {
229 updated_scroll_offset.y = -(item_bottom - list_height) - padding.bottom;
230 }
231 scroll_offset = *updated_scroll_offset;
232 }
233
234 let first_visible_element_ix =
235 (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
236 let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
237 / item_height)
238 .ceil() as usize;
239 let visible_range = first_visible_element_ix
240 ..cmp::min(last_visible_element_ix, self.item_count);
241
242 let mut items = (self.render_items)(visible_range.clone(), cx);
243 cx.with_z_index(1, |cx| {
244 let content_mask = ContentMask { bounds };
245 cx.with_content_mask(Some(content_mask), |cx| {
246 for (item, ix) in items.iter_mut().zip(visible_range) {
247 let item_origin = padded_bounds.origin
248 + point(
249 px(0.),
250 item_height * ix + scroll_offset.y + padding.top,
251 );
252 let available_space = size(
253 AvailableSpace::Definite(padded_bounds.size.width),
254 AvailableSpace::Definite(item_height),
255 );
256 item.draw(item_origin, available_space, cx);
257 }
258 });
259 });
260 }
261 },
262 )
263 }
264}
265
266impl IntoElement for UniformList {
267 type Element = Self;
268
269 fn element_id(&self) -> Option<crate::ElementId> {
270 Some(self.id.clone())
271 }
272
273 fn into_element(self) -> Self::Element {
274 self
275 }
276}
277
278impl UniformList {
279 /// Selects a specific list item for measurement.
280 pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
281 self.item_to_measure_index = item_index.unwrap_or(0);
282 self
283 }
284
285 fn measure_item(&self, list_width: Option<Pixels>, cx: &mut ElementContext) -> Size<Pixels> {
286 if self.item_count == 0 {
287 return Size::default();
288 }
289
290 let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
291 let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
292 let mut item_to_measure = items.pop().unwrap();
293 let available_space = size(
294 list_width.map_or(AvailableSpace::MinContent, |width| {
295 AvailableSpace::Definite(width)
296 }),
297 AvailableSpace::MinContent,
298 );
299 item_to_measure.measure(available_space, cx)
300 }
301
302 /// Track and render scroll state of this list with reference to the given scroll handle.
303 pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
304 self.interactivity.scroll_handle = Some(handle.base_handle.clone());
305 self.scroll_handle = Some(handle);
306 self
307 }
308}
309
310impl InteractiveElement for UniformList {
311 fn interactivity(&mut self) -> &mut crate::Interactivity {
312 &mut self.interactivity
313 }
314}