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