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