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 AnyElement, App, AvailableSpace, Bounds, ContentMask, Element, ElementId, Entity,
9 GlobalElementId, Hitbox, InspectorElementId, InteractiveElement, Interactivity, IntoElement,
10 IsZero, LayoutId, ListSizingBehavior, Overflow, Pixels, Point, ScrollHandle, Size,
11 StyleRefinement, Styled, Window, point, size,
12};
13use smallvec::SmallVec;
14use std::{cell::RefCell, cmp, ops::Range, rc::Rc};
15
16use super::ListHorizontalSizingBehavior;
17
18/// uniform_list provides lazy rendering for a set of items that are of uniform height.
19/// When rendered into a container with overflow-y: hidden and a fixed (or max) height,
20/// uniform_list will only render the visible subset of items.
21#[track_caller]
22pub fn uniform_list<R>(
23 id: impl Into<ElementId>,
24 item_count: usize,
25 f: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
26) -> UniformList
27where
28 R: IntoElement,
29{
30 let id = id.into();
31 let mut base_style = StyleRefinement::default();
32 base_style.overflow.y = Some(Overflow::Scroll);
33
34 let render_range = move |range: Range<usize>, window: &mut Window, cx: &mut App| {
35 f(range, window, cx)
36 .into_iter()
37 .map(|component| component.into_any_element())
38 .collect()
39 };
40
41 UniformList {
42 item_count,
43 item_to_measure_index: 0,
44 render_items: Box::new(render_range),
45 decorations: Vec::new(),
46 interactivity: Interactivity {
47 element_id: Some(id),
48 base_style: Box::new(base_style),
49 ..Interactivity::new()
50 },
51 scroll_handle: None,
52 sizing_behavior: ListSizingBehavior::default(),
53 horizontal_sizing_behavior: ListHorizontalSizingBehavior::default(),
54 }
55}
56
57/// A list element for efficiently laying out and displaying a list of uniform-height elements.
58pub struct UniformList {
59 item_count: usize,
60 item_to_measure_index: usize,
61 render_items: Box<
62 dyn for<'a> Fn(Range<usize>, &'a mut Window, &'a mut App) -> SmallVec<[AnyElement; 64]>,
63 >,
64 decorations: Vec<Box<dyn UniformListDecoration>>,
65 interactivity: Interactivity,
66 scroll_handle: Option<UniformListScrollHandle>,
67 sizing_behavior: ListSizingBehavior,
68 horizontal_sizing_behavior: ListHorizontalSizingBehavior,
69}
70
71/// Frame state used by the [UniformList].
72pub struct UniformListFrameState {
73 items: SmallVec<[AnyElement; 32]>,
74 decorations: SmallVec<[AnyElement; 2]>,
75}
76
77/// A handle for controlling the scroll position of a uniform list.
78/// This should be stored in your view and passed to the uniform_list on each frame.
79#[derive(Clone, Debug, Default)]
80pub struct UniformListScrollHandle(pub Rc<RefCell<UniformListScrollState>>);
81
82/// Where to place the element scrolled to.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum ScrollStrategy {
85 /// Place the element at the top of the list's viewport.
86 Top,
87 /// Attempt to place the element in the middle of the list's viewport.
88 /// May not be possible if there's not enough list items above the item scrolled to:
89 /// in this case, the element will be placed at the closest possible position.
90 Center,
91}
92
93#[derive(Clone, Copy, Debug)]
94#[allow(missing_docs)]
95pub struct DeferredScrollToItem {
96 /// The item index to scroll to
97 pub item_index: usize,
98 /// The scroll strategy to use
99 pub strategy: ScrollStrategy,
100 /// The offset in number of items
101 pub offset: usize,
102}
103
104#[derive(Clone, Debug, Default)]
105#[allow(missing_docs)]
106pub struct UniformListScrollState {
107 pub base_handle: ScrollHandle,
108 pub deferred_scroll_to_item: Option<DeferredScrollToItem>,
109 /// Size of the item, captured during last layout.
110 pub last_item_size: Option<ItemSize>,
111 /// Whether the list was vertically flipped during last layout.
112 pub y_flipped: bool,
113}
114
115#[derive(Copy, Clone, Debug, Default)]
116/// The size of the item and its contents.
117pub struct ItemSize {
118 /// The size of the item.
119 pub item: Size<Pixels>,
120 /// The size of the item's contents, which may be larger than the item itself,
121 /// if the item was bounded by a parent element.
122 pub contents: Size<Pixels>,
123}
124
125impl UniformListScrollHandle {
126 /// Create a new scroll handle to bind to a uniform list.
127 pub fn new() -> Self {
128 Self(Rc::new(RefCell::new(UniformListScrollState {
129 base_handle: ScrollHandle::new(),
130 deferred_scroll_to_item: None,
131 last_item_size: None,
132 y_flipped: false,
133 })))
134 }
135
136 /// Scroll the list to the given item index.
137 pub fn scroll_to_item(&self, ix: usize, strategy: ScrollStrategy) {
138 self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
139 item_index: ix,
140 strategy,
141 offset: 0,
142 });
143 }
144
145 /// Scroll the list to the given item index with an offset.
146 ///
147 /// For ScrollStrategy::Top, the item will be placed at the offset position from the top.
148 ///
149 /// For ScrollStrategy::Center, the item will be centered between offset and the last visible item.
150 pub fn scroll_to_item_with_offset(&self, ix: usize, strategy: ScrollStrategy, offset: usize) {
151 self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
152 item_index: ix,
153 strategy,
154 offset,
155 });
156 }
157
158 /// Check if the list is flipped vertically.
159 pub fn y_flipped(&self) -> bool {
160 self.0.borrow().y_flipped
161 }
162
163 /// Get the index of the topmost visible child.
164 #[cfg(any(test, feature = "test-support"))]
165 pub fn logical_scroll_top_index(&self) -> usize {
166 let this = self.0.borrow();
167 this.deferred_scroll_to_item
168 .as_ref()
169 .map(|deferred| deferred.item_index)
170 .unwrap_or_else(|| this.base_handle.logical_scroll_top().0)
171 }
172
173 /// Checks if the list can be scrolled vertically.
174 pub fn is_scrollable(&self) -> bool {
175 if let Some(size) = self.0.borrow().last_item_size {
176 size.contents.height > size.item.height
177 } else {
178 false
179 }
180 }
181}
182
183impl Styled for UniformList {
184 fn style(&mut self) -> &mut StyleRefinement {
185 &mut self.interactivity.base_style
186 }
187}
188
189impl Element for UniformList {
190 type RequestLayoutState = UniformListFrameState;
191 type PrepaintState = Option<Hitbox>;
192
193 fn id(&self) -> Option<ElementId> {
194 self.interactivity.element_id.clone()
195 }
196
197 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
198 None
199 }
200
201 fn request_layout(
202 &mut self,
203 global_id: Option<&GlobalElementId>,
204 inspector_id: Option<&InspectorElementId>,
205 window: &mut Window,
206 cx: &mut App,
207 ) -> (LayoutId, Self::RequestLayoutState) {
208 let max_items = self.item_count;
209 let item_size = self.measure_item(None, window, cx);
210 let layout_id = self.interactivity.request_layout(
211 global_id,
212 inspector_id,
213 window,
214 cx,
215 |style, window, cx| match self.sizing_behavior {
216 ListSizingBehavior::Infer => {
217 window.with_text_style(style.text_style().cloned(), |window| {
218 window.request_measured_layout(
219 style,
220 move |known_dimensions, available_space, _window, _cx| {
221 let desired_height = item_size.height * max_items;
222 let width = known_dimensions.width.unwrap_or(match available_space
223 .width
224 {
225 AvailableSpace::Definite(x) => x,
226 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
227 item_size.width
228 }
229 });
230 let height = match available_space.height {
231 AvailableSpace::Definite(height) => desired_height.min(height),
232 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
233 desired_height
234 }
235 };
236 size(width, height)
237 },
238 )
239 })
240 }
241 ListSizingBehavior::Auto => window
242 .with_text_style(style.text_style().cloned(), |window| {
243 window.request_layout(style, None, cx)
244 }),
245 },
246 );
247
248 (
249 layout_id,
250 UniformListFrameState {
251 items: SmallVec::new(),
252 decorations: SmallVec::new(),
253 },
254 )
255 }
256
257 fn prepaint(
258 &mut self,
259 global_id: Option<&GlobalElementId>,
260 inspector_id: Option<&InspectorElementId>,
261 bounds: Bounds<Pixels>,
262 frame_state: &mut Self::RequestLayoutState,
263 window: &mut Window,
264 cx: &mut App,
265 ) -> Option<Hitbox> {
266 let style = self
267 .interactivity
268 .compute_style(global_id, None, window, cx);
269 let border = style.border_widths.to_pixels(window.rem_size());
270 let padding = style
271 .padding
272 .to_pixels(bounds.size.into(), window.rem_size());
273
274 let padded_bounds = Bounds::from_corners(
275 bounds.origin + point(border.left + padding.left, border.top + padding.top),
276 bounds.bottom_right()
277 - point(border.right + padding.right, border.bottom + padding.bottom),
278 );
279
280 let can_scroll_horizontally = matches!(
281 self.horizontal_sizing_behavior,
282 ListHorizontalSizingBehavior::Unconstrained
283 );
284
285 let longest_item_size = self.measure_item(None, window, cx);
286 let content_width = if can_scroll_horizontally {
287 padded_bounds.size.width.max(longest_item_size.width)
288 } else {
289 padded_bounds.size.width
290 };
291 let content_size = Size {
292 width: content_width,
293 height: longest_item_size.height * self.item_count + padding.top + padding.bottom,
294 };
295
296 let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
297 let item_height = longest_item_size.height;
298 let shared_scroll_to_item = self.scroll_handle.as_mut().and_then(|handle| {
299 let mut handle = handle.0.borrow_mut();
300 handle.last_item_size = Some(ItemSize {
301 item: padded_bounds.size,
302 contents: content_size,
303 });
304 handle.deferred_scroll_to_item.take()
305 });
306
307 self.interactivity.prepaint(
308 global_id,
309 inspector_id,
310 bounds,
311 content_size,
312 window,
313 cx,
314 |style, mut scroll_offset, hitbox, window, cx| {
315 let border = style.border_widths.to_pixels(window.rem_size());
316 let padding = style
317 .padding
318 .to_pixels(bounds.size.into(), window.rem_size());
319
320 let padded_bounds = Bounds::from_corners(
321 bounds.origin + point(border.left + padding.left, border.top),
322 bounds.bottom_right() - point(border.right + padding.right, border.bottom),
323 );
324
325 let y_flipped = if let Some(scroll_handle) = &self.scroll_handle {
326 let scroll_state = scroll_handle.0.borrow();
327 scroll_state.y_flipped
328 } else {
329 false
330 };
331
332 if self.item_count > 0 {
333 let content_height =
334 item_height * self.item_count + padding.top + padding.bottom;
335 let is_scrolled_vertically = !scroll_offset.y.is_zero();
336 let min_vertical_scroll_offset = padded_bounds.size.height - content_height;
337 if is_scrolled_vertically && scroll_offset.y < min_vertical_scroll_offset {
338 shared_scroll_offset.borrow_mut().y = min_vertical_scroll_offset;
339 scroll_offset.y = min_vertical_scroll_offset;
340 }
341
342 let content_width = content_size.width + padding.left + padding.right;
343 let is_scrolled_horizontally =
344 can_scroll_horizontally && !scroll_offset.x.is_zero();
345 if is_scrolled_horizontally && content_width <= padded_bounds.size.width {
346 shared_scroll_offset.borrow_mut().x = Pixels::ZERO;
347 scroll_offset.x = Pixels::ZERO;
348 }
349
350 if let Some(deferred_scroll) = shared_scroll_to_item {
351 let mut ix = deferred_scroll.item_index;
352 if y_flipped {
353 ix = self.item_count.saturating_sub(ix + 1);
354 }
355 let list_height = padded_bounds.size.height;
356 let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
357 let item_top = item_height * ix + padding.top;
358 let item_bottom = item_top + item_height;
359 let scroll_top = -updated_scroll_offset.y;
360 let offset_pixels = item_height * deferred_scroll.offset;
361 let mut scrolled_to_top = false;
362
363 if item_top < scroll_top + padding.top + offset_pixels {
364 scrolled_to_top = true;
365 updated_scroll_offset.y = -(item_top) + padding.top + offset_pixels;
366 } else if item_bottom > scroll_top + list_height - padding.bottom {
367 scrolled_to_top = true;
368 updated_scroll_offset.y = -(item_bottom - list_height) - padding.bottom;
369 }
370
371 match deferred_scroll.strategy {
372 ScrollStrategy::Top => {}
373 ScrollStrategy::Center => {
374 if scrolled_to_top {
375 let item_center = item_top + item_height / 2.0;
376
377 let viewport_height = list_height - offset_pixels;
378 let viewport_center = offset_pixels + viewport_height / 2.0;
379 let target_scroll_top = item_center - viewport_center;
380
381 if item_top < scroll_top + offset_pixels
382 || item_bottom > scroll_top + list_height
383 {
384 updated_scroll_offset.y = -target_scroll_top
385 .max(Pixels::ZERO)
386 .min(content_height - list_height)
387 .max(Pixels::ZERO);
388 }
389 }
390 }
391 }
392 scroll_offset = *updated_scroll_offset
393 }
394
395 let first_visible_element_ix =
396 (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
397 let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
398 / item_height)
399 .ceil() as usize;
400
401 let visible_range = first_visible_element_ix
402 ..cmp::min(last_visible_element_ix, self.item_count);
403
404 let items = if y_flipped {
405 let flipped_range = self.item_count.saturating_sub(visible_range.end)
406 ..self.item_count.saturating_sub(visible_range.start);
407 let mut items = (self.render_items)(flipped_range, window, cx);
408 items.reverse();
409 items
410 } else {
411 (self.render_items)(visible_range.clone(), window, cx)
412 };
413
414 let content_mask = ContentMask { bounds };
415 window.with_content_mask(Some(content_mask), |window| {
416 for (mut item, ix) in items.into_iter().zip(visible_range.clone()) {
417 let item_origin = padded_bounds.origin
418 + point(
419 if can_scroll_horizontally {
420 scroll_offset.x + padding.left
421 } else {
422 scroll_offset.x
423 },
424 item_height * ix + scroll_offset.y + padding.top,
425 );
426 let available_width = if can_scroll_horizontally {
427 padded_bounds.size.width + scroll_offset.x.abs()
428 } else {
429 padded_bounds.size.width
430 };
431 let available_space = size(
432 AvailableSpace::Definite(available_width),
433 AvailableSpace::Definite(item_height),
434 );
435 item.layout_as_root(available_space, window, cx);
436 item.prepaint_at(item_origin, window, cx);
437 frame_state.items.push(item);
438 }
439
440 let bounds = Bounds::new(
441 padded_bounds.origin
442 + point(
443 if can_scroll_horizontally {
444 scroll_offset.x + padding.left
445 } else {
446 scroll_offset.x
447 },
448 scroll_offset.y + padding.top,
449 ),
450 padded_bounds.size,
451 );
452 for decoration in &self.decorations {
453 let mut decoration = decoration.as_ref().compute(
454 visible_range.clone(),
455 bounds,
456 scroll_offset,
457 item_height,
458 self.item_count,
459 window,
460 cx,
461 );
462 let available_space = size(
463 AvailableSpace::Definite(bounds.size.width),
464 AvailableSpace::Definite(bounds.size.height),
465 );
466 decoration.layout_as_root(available_space, window, cx);
467 decoration.prepaint_at(bounds.origin, window, cx);
468 frame_state.decorations.push(decoration);
469 }
470 });
471 }
472
473 hitbox
474 },
475 )
476 }
477
478 fn paint(
479 &mut self,
480 global_id: Option<&GlobalElementId>,
481 inspector_id: Option<&InspectorElementId>,
482 bounds: Bounds<crate::Pixels>,
483 request_layout: &mut Self::RequestLayoutState,
484 hitbox: &mut Option<Hitbox>,
485 window: &mut Window,
486 cx: &mut App,
487 ) {
488 self.interactivity.paint(
489 global_id,
490 inspector_id,
491 bounds,
492 hitbox.as_ref(),
493 window,
494 cx,
495 |_, window, cx| {
496 for item in &mut request_layout.items {
497 item.paint(window, cx);
498 }
499 for decoration in &mut request_layout.decorations {
500 decoration.paint(window, cx);
501 }
502 },
503 )
504 }
505}
506
507impl IntoElement for UniformList {
508 type Element = Self;
509
510 fn into_element(self) -> Self::Element {
511 self
512 }
513}
514
515/// A decoration for a [`UniformList`]. This can be used for various things,
516/// such as rendering indent guides, or other visual effects.
517pub trait UniformListDecoration {
518 /// Compute the decoration element, given the visible range of list items,
519 /// the bounds of the list, and the height of each item.
520 fn compute(
521 &self,
522 visible_range: Range<usize>,
523 bounds: Bounds<Pixels>,
524 scroll_offset: Point<Pixels>,
525 item_height: Pixels,
526 item_count: usize,
527 window: &mut Window,
528 cx: &mut App,
529 ) -> AnyElement;
530}
531
532impl<T: UniformListDecoration + 'static> UniformListDecoration for Entity<T> {
533 fn compute(
534 &self,
535 visible_range: Range<usize>,
536 bounds: Bounds<Pixels>,
537 scroll_offset: Point<Pixels>,
538 item_height: Pixels,
539 item_count: usize,
540 window: &mut Window,
541 cx: &mut App,
542 ) -> AnyElement {
543 self.update(cx, |inner, cx| {
544 inner.compute(
545 visible_range,
546 bounds,
547 scroll_offset,
548 item_height,
549 item_count,
550 window,
551 cx,
552 )
553 })
554 }
555}
556
557impl UniformList {
558 /// Selects a specific list item for measurement.
559 pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
560 self.item_to_measure_index = item_index.unwrap_or(0);
561 self
562 }
563
564 /// Sets the sizing behavior, similar to the `List` element.
565 pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
566 self.sizing_behavior = behavior;
567 self
568 }
569
570 /// Sets the horizontal sizing behavior, controlling the way list items laid out horizontally.
571 /// With [`ListHorizontalSizingBehavior::Unconstrained`] behavior, every item and the list itself will
572 /// have the size of the widest item and lay out pushing the `end_slot` to the right end.
573 pub fn with_horizontal_sizing_behavior(
574 mut self,
575 behavior: ListHorizontalSizingBehavior,
576 ) -> Self {
577 self.horizontal_sizing_behavior = behavior;
578 match behavior {
579 ListHorizontalSizingBehavior::FitList => {
580 self.interactivity.base_style.overflow.x = None;
581 }
582 ListHorizontalSizingBehavior::Unconstrained => {
583 self.interactivity.base_style.overflow.x = Some(Overflow::Scroll);
584 }
585 }
586 self
587 }
588
589 /// Adds a decoration element to the list.
590 pub fn with_decoration(mut self, decoration: impl UniformListDecoration + 'static) -> Self {
591 self.decorations.push(Box::new(decoration));
592 self
593 }
594
595 fn measure_item(
596 &self,
597 list_width: Option<Pixels>,
598 window: &mut Window,
599 cx: &mut App,
600 ) -> Size<Pixels> {
601 if self.item_count == 0 {
602 return Size::default();
603 }
604
605 let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
606 let mut items = (self.render_items)(item_ix..item_ix + 1, window, cx);
607 let Some(mut item_to_measure) = items.pop() else {
608 return Size::default();
609 };
610 let available_space = size(
611 list_width.map_or(AvailableSpace::MinContent, |width| {
612 AvailableSpace::Definite(width)
613 }),
614 AvailableSpace::MinContent,
615 );
616 item_to_measure.layout_as_root(available_space, window, cx)
617 }
618
619 /// Track and render scroll state of this list with reference to the given scroll handle.
620 pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
621 self.interactivity.tracked_scroll_handle = Some(handle.0.borrow().base_handle.clone());
622 self.scroll_handle = Some(handle);
623 self
624 }
625
626 /// Sets whether the list is flipped vertically, such that item 0 appears at the bottom.
627 pub fn y_flipped(mut self, y_flipped: bool) -> Self {
628 if let Some(ref scroll_handle) = self.scroll_handle {
629 let mut scroll_state = scroll_handle.0.borrow_mut();
630 let mut base_handle = &scroll_state.base_handle;
631 let offset = base_handle.offset();
632 match scroll_state.last_item_size {
633 Some(last_size) if scroll_state.y_flipped != y_flipped => {
634 let new_y_offset =
635 -(offset.y + last_size.contents.height - last_size.item.height);
636 base_handle.set_offset(point(offset.x, new_y_offset));
637 scroll_state.y_flipped = y_flipped;
638 }
639 // Handle case where list is initially flipped.
640 None if y_flipped => {
641 base_handle.set_offset(point(offset.x, Pixels::MIN));
642 scroll_state.y_flipped = y_flipped;
643 }
644 _ => {}
645 }
646 }
647 self
648 }
649}
650
651impl InteractiveElement for UniformList {
652 fn interactivity(&mut self) -> &mut crate::Interactivity {
653 &mut self.interactivity
654 }
655}