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 // self.max_found_width = 0.0
255 //
256 fn request_layout(
257 &mut self,
258 global_id: Option<&GlobalElementId>,
259 inspector_id: Option<&InspectorElementId>,
260 window: &mut Window,
261 cx: &mut App,
262 ) -> (LayoutId, Self::RequestLayoutState) {
263 let max_items = self.item_count;
264 let item_size = self.measure_item(None, window, cx);
265 let layout_id = self.interactivity.request_layout(
266 global_id,
267 inspector_id,
268 window,
269 cx,
270 |style, window, cx| match self.sizing_behavior {
271 ListSizingBehavior::Infer => {
272 window.with_text_style(style.text_style().cloned(), |window| {
273 window.request_measured_layout(
274 style,
275 move |known_dimensions, available_space, _window, _cx| {
276 let desired_height = item_size.height * max_items;
277 let width = known_dimensions.width.unwrap_or(match available_space
278 .width
279 {
280 AvailableSpace::Definite(x) => x,
281 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
282 item_size.width
283 }
284 });
285 let height = match available_space.height {
286 AvailableSpace::Definite(height) => desired_height.min(height),
287 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
288 desired_height
289 }
290 };
291 size(width, height)
292 },
293 )
294 })
295 }
296 ListSizingBehavior::Auto => window
297 .with_text_style(style.text_style().cloned(), |window| {
298 window.request_layout(style, None, cx)
299 }),
300 },
301 );
302
303 (
304 layout_id,
305 UniformListFrameState {
306 items: SmallVec::new(),
307 decorations: SmallVec::new(),
308 },
309 )
310 }
311
312 fn prepaint(
313 &mut self,
314 global_id: Option<&GlobalElementId>,
315 inspector_id: Option<&InspectorElementId>,
316 bounds: Bounds<Pixels>,
317 frame_state: &mut Self::RequestLayoutState,
318 window: &mut Window,
319 cx: &mut App,
320 ) -> Option<Hitbox> {
321 let style = self
322 .interactivity
323 .compute_style(global_id, None, window, cx);
324 let border = style.border_widths.to_pixels(window.rem_size());
325 let padding = style
326 .padding
327 .to_pixels(bounds.size.into(), window.rem_size());
328
329 let padded_bounds = Bounds::from_corners(
330 bounds.origin + point(border.left + padding.left, border.top + padding.top),
331 bounds.bottom_right()
332 - point(border.right + padding.right, border.bottom + padding.bottom),
333 );
334
335 let can_scroll_horizontally = matches!(
336 self.horizontal_sizing_behavior,
337 ListHorizontalSizingBehavior::Unconstrained
338 );
339
340 let longest_item_size = self.measure_item(None, window, cx);
341 let content_width = if can_scroll_horizontally {
342 padded_bounds.size.width.max(longest_item_size.width)
343 } else {
344 padded_bounds.size.width
345 };
346 let content_size = Size {
347 width: content_width,
348 height: longest_item_size.height * self.item_count,
349 };
350
351 let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
352 let item_height = longest_item_size.height;
353 let shared_scroll_to_item = self.scroll_handle.as_mut().and_then(|handle| {
354 let mut handle = handle.0.borrow_mut();
355 handle.last_item_size = Some(ItemSize {
356 item: padded_bounds.size,
357 contents: content_size,
358 });
359 handle.deferred_scroll_to_item.take()
360 });
361
362 self.interactivity.prepaint(
363 global_id,
364 inspector_id,
365 bounds,
366 content_size,
367 window,
368 cx,
369 |_style, mut scroll_offset, hitbox, window, cx| {
370 let y_flipped = if let Some(scroll_handle) = &self.scroll_handle {
371 let scroll_state = scroll_handle.0.borrow();
372 scroll_state.y_flipped
373 } else {
374 false
375 };
376
377 if self.item_count > 0 {
378 let content_height = item_height * self.item_count;
379
380 let is_scrolled_vertically = !scroll_offset.y.is_zero();
381 let max_scroll_offset = padded_bounds.size.height - content_height;
382
383 if is_scrolled_vertically && scroll_offset.y < max_scroll_offset {
384 shared_scroll_offset.borrow_mut().y = max_scroll_offset;
385 scroll_offset.y = max_scroll_offset;
386 }
387
388 let content_width = content_size.width + padding.left + padding.right;
389 let is_scrolled_horizontally =
390 can_scroll_horizontally && !scroll_offset.x.is_zero();
391 if is_scrolled_horizontally && content_width <= padded_bounds.size.width {
392 shared_scroll_offset.borrow_mut().x = Pixels::ZERO;
393 scroll_offset.x = Pixels::ZERO;
394 }
395
396 if let Some(deferred_scroll) = shared_scroll_to_item {
397 let mut ix = deferred_scroll.item_index;
398 if y_flipped {
399 ix = self.item_count.saturating_sub(ix + 1);
400 }
401 let list_height = padded_bounds.size.height;
402 let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
403 let item_top = item_height * ix;
404 let item_bottom = item_top + item_height;
405 let scroll_top = -updated_scroll_offset.y;
406 let offset_pixels = item_height * deferred_scroll.offset;
407 let mut scrolled_to_top = false;
408
409 if item_top < scroll_top + offset_pixels {
410 scrolled_to_top = true;
411 // todo: using the padding here is wrong - this only works well for few scenarios
412 updated_scroll_offset.y = -item_top + padding.top + offset_pixels;
413 } else if item_bottom > scroll_top + list_height {
414 scrolled_to_top = true;
415 updated_scroll_offset.y = -(item_bottom - list_height);
416 }
417
418 if deferred_scroll.scroll_strict
419 || (scrolled_to_top
420 && (item_top < scroll_top + offset_pixels
421 || item_bottom > scroll_top + list_height))
422 {
423 match deferred_scroll.strategy {
424 ScrollStrategy::Top => {
425 updated_scroll_offset.y = -(item_top - offset_pixels)
426 .max(Pixels::ZERO)
427 .min(content_height - list_height)
428 .max(Pixels::ZERO);
429 }
430 ScrollStrategy::Center => {
431 let item_center = item_top + item_height / 2.0;
432
433 let viewport_height = list_height - offset_pixels;
434 let viewport_center = offset_pixels + viewport_height / 2.0;
435 let target_scroll_top = item_center - viewport_center;
436
437 updated_scroll_offset.y = -target_scroll_top
438 .max(Pixels::ZERO)
439 .min(content_height - list_height)
440 .max(Pixels::ZERO);
441 }
442 ScrollStrategy::Bottom => {
443 updated_scroll_offset.y = -(item_bottom - list_height
444 + offset_pixels)
445 .max(Pixels::ZERO)
446 .min(content_height - list_height)
447 .max(Pixels::ZERO);
448 }
449 }
450 }
451 scroll_offset = *updated_scroll_offset
452 }
453
454 let first_visible_element_ix =
455 (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
456 let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
457 / item_height)
458 .ceil() as usize;
459
460 let visible_range = first_visible_element_ix
461 ..cmp::min(last_visible_element_ix, self.item_count);
462
463 let items = if y_flipped {
464 let flipped_range = self.item_count.saturating_sub(visible_range.end)
465 ..self.item_count.saturating_sub(visible_range.start);
466 let mut items = (self.render_items)(flipped_range, window, cx);
467 items.reverse();
468 items
469 } else {
470 (self.render_items)(visible_range.clone(), window, cx)
471 };
472
473 let content_mask = ContentMask { bounds };
474 window.with_content_mask(Some(content_mask), |window| {
475 for (mut item, ix) in items.into_iter().zip(visible_range.clone()) {
476 let item_origin = padded_bounds.origin
477 + scroll_offset
478 + point(Pixels::ZERO, item_height * ix);
479
480 let available_width = if can_scroll_horizontally {
481 padded_bounds.size.width + scroll_offset.x.abs()
482 } else {
483 padded_bounds.size.width
484 };
485 let available_space = size(
486 AvailableSpace::Definite(available_width),
487 AvailableSpace::Definite(item_height),
488 );
489 item.layout_as_root(available_space, window, cx);
490 item.prepaint_at(item_origin, window, cx);
491 frame_state.items.push(item);
492 }
493
494 let bounds =
495 Bounds::new(padded_bounds.origin + scroll_offset, padded_bounds.size);
496 for decoration in &self.decorations {
497 let mut decoration = decoration.as_ref().compute(
498 visible_range.clone(),
499 bounds,
500 scroll_offset,
501 item_height,
502 self.item_count,
503 window,
504 cx,
505 );
506 let available_space = size(
507 AvailableSpace::Definite(bounds.size.width),
508 AvailableSpace::Definite(bounds.size.height),
509 );
510 decoration.layout_as_root(available_space, window, cx);
511 decoration.prepaint_at(bounds.origin, window, cx);
512 frame_state.decorations.push(decoration);
513 }
514 });
515 }
516
517 hitbox
518 },
519 )
520 }
521
522 fn paint(
523 &mut self,
524 global_id: Option<&GlobalElementId>,
525 inspector_id: Option<&InspectorElementId>,
526 bounds: Bounds<crate::Pixels>,
527 request_layout: &mut Self::RequestLayoutState,
528 hitbox: &mut Option<Hitbox>,
529 window: &mut Window,
530 cx: &mut App,
531 ) {
532 self.interactivity.paint(
533 global_id,
534 inspector_id,
535 bounds,
536 hitbox.as_ref(),
537 window,
538 cx,
539 |_, window, cx| {
540 for item in &mut request_layout.items {
541 item.paint(window, cx);
542 }
543 for decoration in &mut request_layout.decorations {
544 decoration.paint(window, cx);
545 }
546 },
547 )
548 }
549}
550
551impl IntoElement for UniformList {
552 type Element = Self;
553
554 fn into_element(self) -> Self::Element {
555 self
556 }
557}
558
559/// A decoration for a [`UniformList`]. This can be used for various things,
560/// such as rendering indent guides, or other visual effects.
561pub trait UniformListDecoration {
562 /// Compute the decoration element, given the visible range of list items,
563 /// the bounds of the list, and the height of each item.
564 fn compute(
565 &self,
566 visible_range: Range<usize>,
567 bounds: Bounds<Pixels>,
568 scroll_offset: Point<Pixels>,
569 item_height: Pixels,
570 item_count: usize,
571 window: &mut Window,
572 cx: &mut App,
573 ) -> AnyElement;
574}
575
576impl<T: UniformListDecoration + 'static> UniformListDecoration for Entity<T> {
577 fn compute(
578 &self,
579 visible_range: Range<usize>,
580 bounds: Bounds<Pixels>,
581 scroll_offset: Point<Pixels>,
582 item_height: Pixels,
583 item_count: usize,
584 window: &mut Window,
585 cx: &mut App,
586 ) -> AnyElement {
587 self.update(cx, |inner, cx| {
588 inner.compute(
589 visible_range,
590 bounds,
591 scroll_offset,
592 item_height,
593 item_count,
594 window,
595 cx,
596 )
597 })
598 }
599}
600
601impl UniformList {
602 /// Selects a specific list item for measurement.
603 pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
604 self.item_to_measure_index = item_index.unwrap_or(0);
605 self
606 }
607
608 /// Sets the sizing behavior, similar to the `List` element.
609 pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
610 self.sizing_behavior = behavior;
611 self
612 }
613
614 /// Sets the horizontal sizing behavior, controlling the way list items laid out horizontally.
615 /// With [`ListHorizontalSizingBehavior::Unconstrained`] behavior, every item and the list itself will
616 /// have the size of the widest item and lay out pushing the `end_slot` to the right end.
617 pub fn with_horizontal_sizing_behavior(
618 mut self,
619 behavior: ListHorizontalSizingBehavior,
620 ) -> Self {
621 self.horizontal_sizing_behavior = behavior;
622 match behavior {
623 ListHorizontalSizingBehavior::FitList => {
624 self.interactivity.base_style.overflow.x = None;
625 }
626 ListHorizontalSizingBehavior::Unconstrained => {
627 self.interactivity.base_style.overflow.x = Some(Overflow::Scroll);
628 }
629 }
630 self
631 }
632
633 /// Adds a decoration element to the list.
634 pub fn with_decoration(mut self, decoration: impl UniformListDecoration + 'static) -> Self {
635 self.decorations.push(Box::new(decoration));
636 self
637 }
638
639 fn measure_item(
640 &self,
641 list_width: Option<Pixels>,
642 window: &mut Window,
643 cx: &mut App,
644 ) -> Size<Pixels> {
645 if self.item_count == 0 {
646 return Size::default();
647 }
648
649 let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
650 let mut items = (self.render_items)(item_ix..item_ix + 1, window, cx);
651 let Some(mut item_to_measure) = items.pop() else {
652 return Size::default();
653 };
654 let available_space = size(
655 list_width.map_or(AvailableSpace::MinContent, |width| {
656 AvailableSpace::Definite(width)
657 }),
658 AvailableSpace::MinContent,
659 );
660 item_to_measure.layout_as_root(available_space, window, cx)
661 }
662
663 /// Track and render scroll state of this list with reference to the given scroll handle.
664 pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
665 self.interactivity.tracked_scroll_handle = Some(handle.0.borrow().base_handle.clone());
666 self.scroll_handle = Some(handle);
667 self
668 }
669
670 /// Sets whether the list is flipped vertically, such that item 0 appears at the bottom.
671 pub fn y_flipped(mut self, y_flipped: bool) -> Self {
672 if let Some(ref scroll_handle) = self.scroll_handle {
673 let mut scroll_state = scroll_handle.0.borrow_mut();
674 let mut base_handle = &scroll_state.base_handle;
675 let offset = base_handle.offset();
676 match scroll_state.last_item_size {
677 Some(last_size) if scroll_state.y_flipped != y_flipped => {
678 let new_y_offset =
679 -(offset.y + last_size.contents.height - last_size.item.height);
680 base_handle.set_offset(point(offset.x, new_y_offset));
681 scroll_state.y_flipped = y_flipped;
682 }
683 // Handle case where list is initially flipped.
684 None if y_flipped => {
685 base_handle.set_offset(point(offset.x, Pixels::MIN));
686 scroll_state.y_flipped = y_flipped;
687 }
688 _ => {}
689 }
690 }
691 self
692 }
693}
694
695impl InteractiveElement for UniformList {
696 fn interactivity(&mut self) -> &mut crate::Interactivity {
697 &mut self.interactivity
698 }
699}