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