1//! A list element that can be used to render a large number of differently sized elements
2//! efficiently. Clients of this API need to ensure that elements outside of the scrolled
3//! area do not change their height for this element to function correctly. If your elements
4//! do change height, notify the list element via [`ListState::splice`] or [`ListState::reset`].
5//! In order to minimize re-renders, this element's state is stored intrusively
6//! on your own views, so that your code can coordinate directly with the list element's cached state.
7//!
8//! If all of your elements are the same height, see [`UniformList`] for a simpler API
9
10use crate::{
11 AnyElement, App, AvailableSpace, Bounds, ContentMask, DispatchPhase, Edges, Element, EntityId,
12 FocusHandle, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, IntoElement,
13 Overflow, Pixels, Point, ScrollDelta, ScrollWheelEvent, Size, Style, StyleRefinement, Styled,
14 Window, point, px, size,
15};
16use collections::VecDeque;
17use refineable::Refineable as _;
18use std::{cell::RefCell, ops::Range, rc::Rc};
19use sum_tree::{Bias, Dimensions, SumTree};
20
21type RenderItemFn = dyn FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static;
22
23/// Construct a new list element
24pub fn list(
25 state: ListState,
26 render_item: impl FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static,
27) -> List {
28 List {
29 state,
30 render_item: Box::new(render_item),
31 style: StyleRefinement::default(),
32 sizing_behavior: ListSizingBehavior::default(),
33 }
34}
35
36/// A list element
37pub struct List {
38 state: ListState,
39 render_item: Box<RenderItemFn>,
40 style: StyleRefinement,
41 sizing_behavior: ListSizingBehavior,
42}
43
44impl List {
45 /// Set the sizing behavior for the list.
46 pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
47 self.sizing_behavior = behavior;
48 self
49 }
50}
51
52/// The list state that views must hold on behalf of the list element.
53#[derive(Clone)]
54pub struct ListState(Rc<RefCell<StateInner>>);
55
56impl std::fmt::Debug for ListState {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 f.write_str("ListState")
59 }
60}
61
62struct StateInner {
63 last_layout_bounds: Option<Bounds<Pixels>>,
64 last_padding: Option<Edges<Pixels>>,
65 items: SumTree<ListItem>,
66 logical_scroll_top: Option<ListOffset>,
67 alignment: ListAlignment,
68 overdraw: Pixels,
69 reset: bool,
70 #[allow(clippy::type_complexity)]
71 scroll_handler: Option<Box<dyn FnMut(&ListScrollEvent, &mut Window, &mut App)>>,
72 scrollbar_drag_start_height: Option<Pixels>,
73}
74
75/// Whether the list is scrolling from top to bottom or bottom to top.
76#[derive(Clone, Copy, Debug, Eq, PartialEq)]
77pub enum ListAlignment {
78 /// The list is scrolling from top to bottom, like most lists.
79 Top,
80 /// The list is scrolling from bottom to top, like a chat log.
81 Bottom,
82}
83
84/// A scroll event that has been converted to be in terms of the list's items.
85pub struct ListScrollEvent {
86 /// The range of items currently visible in the list, after applying the scroll event.
87 pub visible_range: Range<usize>,
88
89 /// The number of items that are currently visible in the list, after applying the scroll event.
90 pub count: usize,
91
92 /// Whether the list has been scrolled.
93 pub is_scrolled: bool,
94}
95
96/// The sizing behavior to apply during layout.
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
98pub enum ListSizingBehavior {
99 /// The list should calculate its size based on the size of its items.
100 Infer,
101 /// The list should not calculate a fixed size.
102 #[default]
103 Auto,
104}
105
106/// The horizontal sizing behavior to apply during layout.
107#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
108pub enum ListHorizontalSizingBehavior {
109 /// List items' width can never exceed the width of the list.
110 #[default]
111 FitList,
112 /// List items' width may go over the width of the list, if any item is wider.
113 Unconstrained,
114}
115
116struct LayoutItemsResponse {
117 max_item_width: Pixels,
118 scroll_top: ListOffset,
119 item_layouts: VecDeque<ItemLayout>,
120}
121
122struct ItemLayout {
123 index: usize,
124 element: AnyElement,
125 size: Size<Pixels>,
126}
127
128/// Frame state used by the [List] element after layout.
129pub struct ListPrepaintState {
130 hitbox: Hitbox,
131 layout: LayoutItemsResponse,
132}
133
134#[derive(Clone)]
135enum ListItem {
136 Unmeasured {
137 focus_handle: Option<FocusHandle>,
138 },
139 Measured {
140 size: Size<Pixels>,
141 focus_handle: Option<FocusHandle>,
142 },
143}
144
145impl ListItem {
146 fn size(&self) -> Option<Size<Pixels>> {
147 if let ListItem::Measured { size, .. } = self {
148 Some(*size)
149 } else {
150 None
151 }
152 }
153
154 fn focus_handle(&self) -> Option<FocusHandle> {
155 match self {
156 ListItem::Unmeasured { focus_handle } | ListItem::Measured { focus_handle, .. } => {
157 focus_handle.clone()
158 }
159 }
160 }
161
162 fn contains_focused(&self, window: &Window, cx: &App) -> bool {
163 match self {
164 ListItem::Unmeasured { focus_handle } | ListItem::Measured { focus_handle, .. } => {
165 focus_handle
166 .as_ref()
167 .is_some_and(|handle| handle.contains_focused(window, cx))
168 }
169 }
170 }
171}
172
173#[derive(Clone, Debug, Default, PartialEq)]
174struct ListItemSummary {
175 count: usize,
176 rendered_count: usize,
177 unrendered_count: usize,
178 height: Pixels,
179 has_focus_handles: bool,
180}
181
182#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
183struct Count(usize);
184
185#[derive(Clone, Debug, Default)]
186struct Height(Pixels);
187
188impl ListState {
189 /// Construct a new list state, for storage on a view.
190 ///
191 /// The overdraw parameter controls how much extra space is rendered
192 /// above and below the visible area. Elements within this area will
193 /// be measured even though they are not visible. This can help ensure
194 /// that the list doesn't flicker or pop in when scrolling.
195 pub fn new(item_count: usize, alignment: ListAlignment, overdraw: Pixels) -> Self {
196 let this = Self(Rc::new(RefCell::new(StateInner {
197 last_layout_bounds: None,
198 last_padding: None,
199 items: SumTree::default(),
200 logical_scroll_top: None,
201 alignment,
202 overdraw,
203 scroll_handler: None,
204 reset: false,
205 scrollbar_drag_start_height: None,
206 })));
207 this.splice(0..0, item_count);
208 this
209 }
210
211 /// Reset this instantiation of the list state.
212 ///
213 /// Note that this will cause scroll events to be dropped until the next paint.
214 pub fn reset(&self, element_count: usize) {
215 let old_count = {
216 let state = &mut *self.0.borrow_mut();
217 state.reset = true;
218 state.logical_scroll_top = None;
219 state.scrollbar_drag_start_height = None;
220 state.items.summary().count
221 };
222
223 self.splice(0..old_count, element_count);
224 }
225
226 /// The number of items in this list.
227 pub fn item_count(&self) -> usize {
228 self.0.borrow().items.summary().count
229 }
230
231 /// Inform the list state that the items in `old_range` have been replaced
232 /// by `count` new items that must be recalculated.
233 pub fn splice(&self, old_range: Range<usize>, count: usize) {
234 self.splice_focusable(old_range, (0..count).map(|_| None))
235 }
236
237 /// Register with the list state that the items in `old_range` have been replaced
238 /// by new items. As opposed to [`splice`], this method allows an iterator of optional focus handles
239 /// to be supplied to properly integrate with items in the list that can be focused. If a focused item
240 /// is scrolled out of view, the list will continue to render it to allow keyboard interaction.
241 pub fn splice_focusable(
242 &self,
243 old_range: Range<usize>,
244 focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
245 ) {
246 let state = &mut *self.0.borrow_mut();
247
248 let mut old_items = state.items.cursor::<Count>(&());
249 let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right);
250 old_items.seek_forward(&Count(old_range.end), Bias::Right);
251
252 let mut spliced_count = 0;
253 new_items.extend(
254 focus_handles.into_iter().map(|focus_handle| {
255 spliced_count += 1;
256 ListItem::Unmeasured { focus_handle }
257 }),
258 &(),
259 );
260 new_items.append(old_items.suffix(), &());
261 drop(old_items);
262 state.items = new_items;
263
264 if let Some(ListOffset {
265 item_ix,
266 offset_in_item,
267 }) = state.logical_scroll_top.as_mut()
268 {
269 if old_range.contains(item_ix) {
270 *item_ix = old_range.start;
271 *offset_in_item = px(0.);
272 } else if old_range.end <= *item_ix {
273 *item_ix = *item_ix - (old_range.end - old_range.start) + spliced_count;
274 }
275 }
276 }
277
278 /// Set a handler that will be called when the list is scrolled.
279 pub fn set_scroll_handler(
280 &self,
281 handler: impl FnMut(&ListScrollEvent, &mut Window, &mut App) + 'static,
282 ) {
283 self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
284 }
285
286 /// Get the current scroll offset, in terms of the list's items.
287 pub fn logical_scroll_top(&self) -> ListOffset {
288 self.0.borrow().logical_scroll_top()
289 }
290
291 /// Scroll the list by the given offset
292 pub fn scroll_by(&self, distance: Pixels) {
293 if distance == px(0.) {
294 return;
295 }
296
297 let current_offset = self.logical_scroll_top();
298 let state = &mut *self.0.borrow_mut();
299 let mut cursor = state.items.cursor::<ListItemSummary>(&());
300 cursor.seek(&Count(current_offset.item_ix), Bias::Right);
301
302 let start_pixel_offset = cursor.start().height + current_offset.offset_in_item;
303 let new_pixel_offset = (start_pixel_offset + distance).max(px(0.));
304 if new_pixel_offset > start_pixel_offset {
305 cursor.seek_forward(&Height(new_pixel_offset), Bias::Right);
306 } else {
307 cursor.seek(&Height(new_pixel_offset), Bias::Right);
308 }
309
310 state.logical_scroll_top = Some(ListOffset {
311 item_ix: cursor.start().count,
312 offset_in_item: new_pixel_offset - cursor.start().height,
313 });
314 }
315
316 /// Scroll the list to the given offset
317 pub fn scroll_to(&self, mut scroll_top: ListOffset) {
318 let state = &mut *self.0.borrow_mut();
319 let item_count = state.items.summary().count;
320 if scroll_top.item_ix >= item_count {
321 scroll_top.item_ix = item_count;
322 scroll_top.offset_in_item = px(0.);
323 }
324
325 state.logical_scroll_top = Some(scroll_top);
326 }
327
328 /// Scroll the list to the given item, such that the item is fully visible.
329 pub fn scroll_to_reveal_item(&self, ix: usize) {
330 let state = &mut *self.0.borrow_mut();
331
332 let mut scroll_top = state.logical_scroll_top();
333 let height = state
334 .last_layout_bounds
335 .map_or(px(0.), |bounds| bounds.size.height);
336 let padding = state.last_padding.unwrap_or_default();
337
338 if ix <= scroll_top.item_ix {
339 scroll_top.item_ix = ix;
340 scroll_top.offset_in_item = px(0.);
341 } else {
342 let mut cursor = state.items.cursor::<ListItemSummary>(&());
343 cursor.seek(&Count(ix + 1), Bias::Right);
344 let bottom = cursor.start().height + padding.top;
345 let goal_top = px(0.).max(bottom - height + padding.bottom);
346
347 cursor.seek(&Height(goal_top), Bias::Left);
348 let start_ix = cursor.start().count;
349 let start_item_top = cursor.start().height;
350
351 if start_ix >= scroll_top.item_ix {
352 scroll_top.item_ix = start_ix;
353 scroll_top.offset_in_item = goal_top - start_item_top;
354 }
355 }
356
357 state.logical_scroll_top = Some(scroll_top);
358 }
359
360 /// Get the bounds for the given item in window coordinates, if it's
361 /// been rendered.
362 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
363 let state = &*self.0.borrow();
364
365 let bounds = state.last_layout_bounds.unwrap_or_default();
366 let scroll_top = state.logical_scroll_top();
367 if ix < scroll_top.item_ix {
368 return None;
369 }
370
371 let mut cursor = state.items.cursor::<Dimensions<Count, Height>>(&());
372 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
373
374 let scroll_top = cursor.start().1.0 + scroll_top.offset_in_item;
375
376 cursor.seek_forward(&Count(ix), Bias::Right);
377 if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
378 let &Dimensions(Count(count), Height(top), _) = cursor.start();
379 if count == ix {
380 let top = bounds.top() + top - scroll_top;
381 return Some(Bounds::from_corners(
382 point(bounds.left(), top),
383 point(bounds.right(), top + size.height),
384 ));
385 }
386 }
387 None
388 }
389
390 /// Call this method when the user starts dragging the scrollbar.
391 ///
392 /// This will prevent the height reported to the scrollbar from changing during the drag
393 /// as items in the overdraw get measured, and help offset scroll position changes accordingly.
394 pub fn scrollbar_drag_started(&self) {
395 let mut state = self.0.borrow_mut();
396 state.scrollbar_drag_start_height = Some(state.items.summary().height);
397 }
398
399 /// Called when the user stops dragging the scrollbar.
400 ///
401 /// See `scrollbar_drag_started`.
402 pub fn scrollbar_drag_ended(&self) {
403 self.0.borrow_mut().scrollbar_drag_start_height.take();
404 }
405
406 /// Set the offset from the scrollbar
407 pub fn set_offset_from_scrollbar(&self, point: Point<Pixels>) {
408 self.0.borrow_mut().set_offset_from_scrollbar(point);
409 }
410
411 /// Returns the maximum scroll offset according to the items we have measured.
412 /// This value remains constant while dragging to prevent the scrollbar from moving away unexpectedly.
413 pub fn max_offset_for_scrollbar(&self) -> Size<Pixels> {
414 let state = self.0.borrow();
415 let bounds = state.last_layout_bounds.unwrap_or_default();
416
417 let height = state
418 .scrollbar_drag_start_height
419 .unwrap_or_else(|| state.items.summary().height);
420
421 Size::new(Pixels::ZERO, Pixels::ZERO.max(height - bounds.size.height))
422 }
423
424 /// Returns the current scroll offset adjusted for the scrollbar
425 pub fn scroll_px_offset_for_scrollbar(&self) -> Point<Pixels> {
426 let state = &self.0.borrow();
427 let logical_scroll_top = state.logical_scroll_top();
428
429 let mut cursor = state.items.cursor::<ListItemSummary>(&());
430 let summary: ListItemSummary =
431 cursor.summary(&Count(logical_scroll_top.item_ix), Bias::Right);
432 let content_height = state.items.summary().height;
433 let drag_offset =
434 // if dragging the scrollbar, we want to offset the point if the height changed
435 content_height - state.scrollbar_drag_start_height.unwrap_or(content_height);
436 let offset = summary.height + logical_scroll_top.offset_in_item - drag_offset;
437
438 Point::new(px(0.), -offset)
439 }
440
441 /// Return the bounds of the viewport in pixels.
442 pub fn viewport_bounds(&self) -> Bounds<Pixels> {
443 self.0.borrow().last_layout_bounds.unwrap_or_default()
444 }
445}
446
447impl StateInner {
448 fn visible_range(&self, height: Pixels, scroll_top: &ListOffset) -> Range<usize> {
449 let mut cursor = self.items.cursor::<ListItemSummary>(&());
450 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
451 let start_y = cursor.start().height + scroll_top.offset_in_item;
452 cursor.seek_forward(&Height(start_y + height), Bias::Left);
453 scroll_top.item_ix..cursor.start().count + 1
454 }
455
456 fn scroll(
457 &mut self,
458 scroll_top: &ListOffset,
459 height: Pixels,
460 delta: Point<Pixels>,
461 current_view: EntityId,
462 window: &mut Window,
463 cx: &mut App,
464 ) {
465 // Drop scroll events after a reset, since we can't calculate
466 // the new logical scroll top without the item heights
467 if self.reset {
468 return;
469 }
470
471 let padding = self.last_padding.unwrap_or_default();
472 let scroll_max =
473 (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
474 let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
475 .max(px(0.))
476 .min(scroll_max);
477
478 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
479 self.logical_scroll_top = None;
480 } else {
481 let mut cursor = self.items.cursor::<ListItemSummary>(&());
482 cursor.seek(&Height(new_scroll_top), Bias::Right);
483 let item_ix = cursor.start().count;
484 let offset_in_item = new_scroll_top - cursor.start().height;
485 self.logical_scroll_top = Some(ListOffset {
486 item_ix,
487 offset_in_item,
488 });
489 }
490
491 if self.scroll_handler.is_some() {
492 let visible_range = self.visible_range(height, scroll_top);
493 self.scroll_handler.as_mut().unwrap()(
494 &ListScrollEvent {
495 visible_range,
496 count: self.items.summary().count,
497 is_scrolled: self.logical_scroll_top.is_some(),
498 },
499 window,
500 cx,
501 );
502 }
503
504 cx.notify(current_view);
505 }
506
507 fn logical_scroll_top(&self) -> ListOffset {
508 self.logical_scroll_top
509 .unwrap_or_else(|| match self.alignment {
510 ListAlignment::Top => ListOffset {
511 item_ix: 0,
512 offset_in_item: px(0.),
513 },
514 ListAlignment::Bottom => ListOffset {
515 item_ix: self.items.summary().count,
516 offset_in_item: px(0.),
517 },
518 })
519 }
520
521 fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
522 let mut cursor = self.items.cursor::<ListItemSummary>(&());
523 cursor.seek(&Count(logical_scroll_top.item_ix), Bias::Right);
524 cursor.start().height + logical_scroll_top.offset_in_item
525 }
526
527 fn layout_items(
528 &mut self,
529 available_width: Option<Pixels>,
530 available_height: Pixels,
531 padding: &Edges<Pixels>,
532 render_item: &mut RenderItemFn,
533 window: &mut Window,
534 cx: &mut App,
535 ) -> LayoutItemsResponse {
536 let old_items = self.items.clone();
537 let mut measured_items = VecDeque::new();
538 let mut item_layouts = VecDeque::new();
539 let mut rendered_height = padding.top;
540 let mut max_item_width = px(0.);
541 let mut scroll_top = self.logical_scroll_top();
542 let mut rendered_focused_item = false;
543
544 let available_item_space = size(
545 available_width.map_or(AvailableSpace::MinContent, |width| {
546 AvailableSpace::Definite(width)
547 }),
548 AvailableSpace::MinContent,
549 );
550
551 let mut cursor = old_items.cursor::<Count>(&());
552
553 // Render items after the scroll top, including those in the trailing overdraw
554 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
555 for (ix, item) in cursor.by_ref().enumerate() {
556 let visible_height = rendered_height - scroll_top.offset_in_item;
557 if visible_height >= available_height + self.overdraw {
558 break;
559 }
560
561 // Use the previously cached height and focus handle if available
562 let mut size = item.size();
563
564 // If we're within the visible area or the height wasn't cached, render and measure the item's element
565 if visible_height < available_height || size.is_none() {
566 let item_index = scroll_top.item_ix + ix;
567 let mut element = render_item(item_index, window, cx);
568 let element_size = element.layout_as_root(available_item_space, window, cx);
569 size = Some(element_size);
570 if visible_height < available_height {
571 item_layouts.push_back(ItemLayout {
572 index: item_index,
573 element,
574 size: element_size,
575 });
576 if item.contains_focused(window, cx) {
577 rendered_focused_item = true;
578 }
579 }
580 }
581
582 let size = size.unwrap();
583 rendered_height += size.height;
584 max_item_width = max_item_width.max(size.width);
585 measured_items.push_back(ListItem::Measured {
586 size,
587 focus_handle: item.focus_handle(),
588 });
589 }
590 rendered_height += padding.bottom;
591
592 // Prepare to start walking upward from the item at the scroll top.
593 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
594
595 // If the rendered items do not fill the visible region, then adjust
596 // the scroll top upward.
597 if rendered_height - scroll_top.offset_in_item < available_height {
598 while rendered_height < available_height {
599 cursor.prev();
600 if let Some(item) = cursor.item() {
601 let item_index = cursor.start().0;
602 let mut element = render_item(item_index, window, cx);
603 let element_size = element.layout_as_root(available_item_space, window, cx);
604 let focus_handle = item.focus_handle();
605 rendered_height += element_size.height;
606 measured_items.push_front(ListItem::Measured {
607 size: element_size,
608 focus_handle,
609 });
610 item_layouts.push_front(ItemLayout {
611 index: item_index,
612 element,
613 size: element_size,
614 });
615 if item.contains_focused(window, cx) {
616 rendered_focused_item = true;
617 }
618 } else {
619 break;
620 }
621 }
622
623 scroll_top = ListOffset {
624 item_ix: cursor.start().0,
625 offset_in_item: rendered_height - available_height,
626 };
627
628 match self.alignment {
629 ListAlignment::Top => {
630 scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
631 self.logical_scroll_top = Some(scroll_top);
632 }
633 ListAlignment::Bottom => {
634 scroll_top = ListOffset {
635 item_ix: cursor.start().0,
636 offset_in_item: rendered_height - available_height,
637 };
638 self.logical_scroll_top = None;
639 }
640 };
641 }
642
643 // Measure items in the leading overdraw
644 let mut leading_overdraw = scroll_top.offset_in_item;
645 while leading_overdraw < self.overdraw {
646 cursor.prev();
647 if let Some(item) = cursor.item() {
648 let size = if let ListItem::Measured { size, .. } = item {
649 *size
650 } else {
651 let mut element = render_item(cursor.start().0, window, cx);
652 element.layout_as_root(available_item_space, window, cx)
653 };
654
655 leading_overdraw += size.height;
656 measured_items.push_front(ListItem::Measured {
657 size,
658 focus_handle: item.focus_handle(),
659 });
660 } else {
661 break;
662 }
663 }
664
665 let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
666 let mut cursor = old_items.cursor::<Count>(&());
667 let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right);
668 new_items.extend(measured_items, &());
669 cursor.seek(&Count(measured_range.end), Bias::Right);
670 new_items.append(cursor.suffix(), &());
671 self.items = new_items;
672
673 // If none of the visible items are focused, check if an off-screen item is focused
674 // and include it to be rendered after the visible items so keyboard interaction continues
675 // to work for it.
676 if !rendered_focused_item {
677 let mut cursor = self
678 .items
679 .filter::<_, Count>(&(), |summary| summary.has_focus_handles);
680 cursor.next();
681 while let Some(item) = cursor.item() {
682 if item.contains_focused(window, cx) {
683 let item_index = cursor.start().0;
684 let mut element = render_item(cursor.start().0, window, cx);
685 let size = element.layout_as_root(available_item_space, window, cx);
686 item_layouts.push_back(ItemLayout {
687 index: item_index,
688 element,
689 size,
690 });
691 break;
692 }
693 cursor.next();
694 }
695 }
696
697 LayoutItemsResponse {
698 max_item_width,
699 scroll_top,
700 item_layouts,
701 }
702 }
703
704 fn prepaint_items(
705 &mut self,
706 bounds: Bounds<Pixels>,
707 padding: Edges<Pixels>,
708 autoscroll: bool,
709 render_item: &mut RenderItemFn,
710 window: &mut Window,
711 cx: &mut App,
712 ) -> Result<LayoutItemsResponse, ListOffset> {
713 window.transact(|window| {
714 let mut layout_response = self.layout_items(
715 Some(bounds.size.width),
716 bounds.size.height,
717 &padding,
718 render_item,
719 window,
720 cx,
721 );
722
723 // Avoid honoring autoscroll requests from elements other than our children.
724 window.take_autoscroll();
725
726 // Only paint the visible items, if there is actually any space for them (taking padding into account)
727 if bounds.size.height > padding.top + padding.bottom {
728 let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
729 item_origin.y -= layout_response.scroll_top.offset_in_item;
730 for item in &mut layout_response.item_layouts {
731 window.with_content_mask(Some(ContentMask { bounds }), |window| {
732 item.element.prepaint_at(item_origin, window, cx);
733 });
734
735 if let Some(autoscroll_bounds) = window.take_autoscroll() {
736 if autoscroll {
737 if autoscroll_bounds.top() < bounds.top() {
738 return Err(ListOffset {
739 item_ix: item.index,
740 offset_in_item: autoscroll_bounds.top() - item_origin.y,
741 });
742 } else if autoscroll_bounds.bottom() > bounds.bottom() {
743 let mut cursor = self.items.cursor::<Count>(&());
744 cursor.seek(&Count(item.index), Bias::Right);
745 let mut height = bounds.size.height - padding.top - padding.bottom;
746
747 // Account for the height of the element down until the autoscroll bottom.
748 height -= autoscroll_bounds.bottom() - item_origin.y;
749
750 // Keep decreasing the scroll top until we fill all the available space.
751 while height > Pixels::ZERO {
752 cursor.prev();
753 let Some(item) = cursor.item() else { break };
754
755 let size = item.size().unwrap_or_else(|| {
756 let mut item = render_item(cursor.start().0, window, cx);
757 let item_available_size = size(
758 bounds.size.width.into(),
759 AvailableSpace::MinContent,
760 );
761 item.layout_as_root(item_available_size, window, cx)
762 });
763 height -= size.height;
764 }
765
766 return Err(ListOffset {
767 item_ix: cursor.start().0,
768 offset_in_item: if height < Pixels::ZERO {
769 -height
770 } else {
771 Pixels::ZERO
772 },
773 });
774 }
775 }
776 }
777
778 item_origin.y += item.size.height;
779 }
780 } else {
781 layout_response.item_layouts.clear();
782 }
783
784 Ok(layout_response)
785 })
786 }
787
788 // Scrollbar support
789
790 fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
791 let Some(bounds) = self.last_layout_bounds else {
792 return;
793 };
794 let height = bounds.size.height;
795
796 let padding = self.last_padding.unwrap_or_default();
797 let content_height = self.items.summary().height;
798 let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
799 let drag_offset =
800 // if dragging the scrollbar, we want to offset the point if the height changed
801 content_height - self.scrollbar_drag_start_height.unwrap_or(content_height);
802 let new_scroll_top = (point.y - drag_offset).abs().max(px(0.)).min(scroll_max);
803
804 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
805 self.logical_scroll_top = None;
806 } else {
807 let mut cursor = self.items.cursor::<ListItemSummary>(&());
808 cursor.seek(&Height(new_scroll_top), Bias::Right);
809
810 let item_ix = cursor.start().count;
811 let offset_in_item = new_scroll_top - cursor.start().height;
812 self.logical_scroll_top = Some(ListOffset {
813 item_ix,
814 offset_in_item,
815 });
816 }
817 }
818}
819
820impl std::fmt::Debug for ListItem {
821 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
822 match self {
823 Self::Unmeasured { .. } => write!(f, "Unrendered"),
824 Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
825 }
826 }
827}
828
829/// An offset into the list's items, in terms of the item index and the number
830/// of pixels off the top left of the item.
831#[derive(Debug, Clone, Copy, Default)]
832pub struct ListOffset {
833 /// The index of an item in the list
834 pub item_ix: usize,
835 /// The number of pixels to offset from the item index.
836 pub offset_in_item: Pixels,
837}
838
839impl Element for List {
840 type RequestLayoutState = ();
841 type PrepaintState = ListPrepaintState;
842
843 fn id(&self) -> Option<crate::ElementId> {
844 None
845 }
846
847 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
848 None
849 }
850
851 fn request_layout(
852 &mut self,
853 _id: Option<&GlobalElementId>,
854 _inspector_id: Option<&InspectorElementId>,
855 window: &mut Window,
856 cx: &mut App,
857 ) -> (crate::LayoutId, Self::RequestLayoutState) {
858 let layout_id = match self.sizing_behavior {
859 ListSizingBehavior::Infer => {
860 let mut style = Style::default();
861 style.overflow.y = Overflow::Scroll;
862 style.refine(&self.style);
863 window.with_text_style(style.text_style().cloned(), |window| {
864 let state = &mut *self.state.0.borrow_mut();
865
866 let available_height = if let Some(last_bounds) = state.last_layout_bounds {
867 last_bounds.size.height
868 } else {
869 // If we don't have the last layout bounds (first render),
870 // we might just use the overdraw value as the available height to layout enough items.
871 state.overdraw
872 };
873 let padding = style.padding.to_pixels(
874 state.last_layout_bounds.unwrap_or_default().size.into(),
875 window.rem_size(),
876 );
877
878 let layout_response = state.layout_items(
879 None,
880 available_height,
881 &padding,
882 &mut self.render_item,
883 window,
884 cx,
885 );
886 let max_element_width = layout_response.max_item_width;
887
888 let summary = state.items.summary();
889 let total_height = summary.height;
890
891 window.request_measured_layout(
892 style,
893 move |known_dimensions, available_space, _window, _cx| {
894 let width =
895 known_dimensions
896 .width
897 .unwrap_or(match available_space.width {
898 AvailableSpace::Definite(x) => x,
899 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
900 max_element_width
901 }
902 });
903 let height = match available_space.height {
904 AvailableSpace::Definite(height) => total_height.min(height),
905 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
906 total_height
907 }
908 };
909 size(width, height)
910 },
911 )
912 })
913 }
914 ListSizingBehavior::Auto => {
915 let mut style = Style::default();
916 style.refine(&self.style);
917 window.with_text_style(style.text_style().cloned(), |window| {
918 window.request_layout(style, None, cx)
919 })
920 }
921 };
922 (layout_id, ())
923 }
924
925 fn prepaint(
926 &mut self,
927 _id: Option<&GlobalElementId>,
928 _inspector_id: Option<&InspectorElementId>,
929 bounds: Bounds<Pixels>,
930 _: &mut Self::RequestLayoutState,
931 window: &mut Window,
932 cx: &mut App,
933 ) -> ListPrepaintState {
934 let state = &mut *self.state.0.borrow_mut();
935 state.reset = false;
936
937 let mut style = Style::default();
938 style.refine(&self.style);
939
940 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
941
942 // If the width of the list has changed, invalidate all cached item heights
943 if state.last_layout_bounds.map_or(true, |last_bounds| {
944 last_bounds.size.width != bounds.size.width
945 }) {
946 let new_items = SumTree::from_iter(
947 state.items.iter().map(|item| ListItem::Unmeasured {
948 focus_handle: item.focus_handle(),
949 }),
950 &(),
951 );
952
953 state.items = new_items;
954 }
955
956 let padding = style
957 .padding
958 .to_pixels(bounds.size.into(), window.rem_size());
959 let layout =
960 match state.prepaint_items(bounds, padding, true, &mut self.render_item, window, cx) {
961 Ok(layout) => layout,
962 Err(autoscroll_request) => {
963 state.logical_scroll_top = Some(autoscroll_request);
964 state
965 .prepaint_items(bounds, padding, false, &mut self.render_item, window, cx)
966 .unwrap()
967 }
968 };
969
970 state.last_layout_bounds = Some(bounds);
971 state.last_padding = Some(padding);
972 ListPrepaintState { hitbox, layout }
973 }
974
975 fn paint(
976 &mut self,
977 _id: Option<&GlobalElementId>,
978 _inspector_id: Option<&InspectorElementId>,
979 bounds: Bounds<crate::Pixels>,
980 _: &mut Self::RequestLayoutState,
981 prepaint: &mut Self::PrepaintState,
982 window: &mut Window,
983 cx: &mut App,
984 ) {
985 let current_view = window.current_view();
986 window.with_content_mask(Some(ContentMask { bounds }), |window| {
987 for item in &mut prepaint.layout.item_layouts {
988 item.element.paint(window, cx);
989 }
990 });
991
992 let list_state = self.state.clone();
993 let height = bounds.size.height;
994 let scroll_top = prepaint.layout.scroll_top;
995 let hitbox_id = prepaint.hitbox.id;
996 let mut accumulated_scroll_delta = ScrollDelta::default();
997 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
998 if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
999 accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
1000 let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1001 list_state.0.borrow_mut().scroll(
1002 &scroll_top,
1003 height,
1004 pixel_delta,
1005 current_view,
1006 window,
1007 cx,
1008 )
1009 }
1010 });
1011 }
1012}
1013
1014impl IntoElement for List {
1015 type Element = Self;
1016
1017 fn into_element(self) -> Self::Element {
1018 self
1019 }
1020}
1021
1022impl Styled for List {
1023 fn style(&mut self) -> &mut StyleRefinement {
1024 &mut self.style
1025 }
1026}
1027
1028impl sum_tree::Item for ListItem {
1029 type Summary = ListItemSummary;
1030
1031 fn summary(&self, _: &()) -> Self::Summary {
1032 match self {
1033 ListItem::Unmeasured { focus_handle } => ListItemSummary {
1034 count: 1,
1035 rendered_count: 0,
1036 unrendered_count: 1,
1037 height: px(0.),
1038 has_focus_handles: focus_handle.is_some(),
1039 },
1040 ListItem::Measured {
1041 size, focus_handle, ..
1042 } => ListItemSummary {
1043 count: 1,
1044 rendered_count: 1,
1045 unrendered_count: 0,
1046 height: size.height,
1047 has_focus_handles: focus_handle.is_some(),
1048 },
1049 }
1050 }
1051}
1052
1053impl sum_tree::Summary for ListItemSummary {
1054 type Context = ();
1055
1056 fn zero(_cx: &()) -> Self {
1057 Default::default()
1058 }
1059
1060 fn add_summary(&mut self, summary: &Self, _: &()) {
1061 self.count += summary.count;
1062 self.rendered_count += summary.rendered_count;
1063 self.unrendered_count += summary.unrendered_count;
1064 self.height += summary.height;
1065 self.has_focus_handles |= summary.has_focus_handles;
1066 }
1067}
1068
1069impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1070 fn zero(_cx: &()) -> Self {
1071 Default::default()
1072 }
1073
1074 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
1075 self.0 += summary.count;
1076 }
1077}
1078
1079impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1080 fn zero(_cx: &()) -> Self {
1081 Default::default()
1082 }
1083
1084 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
1085 self.0 += summary.height;
1086 }
1087}
1088
1089impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1090 fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
1091 self.0.partial_cmp(&other.count).unwrap()
1092 }
1093}
1094
1095impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1096 fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
1097 self.0.partial_cmp(&other.height).unwrap()
1098 }
1099}
1100
1101#[cfg(test)]
1102mod test {
1103
1104 use gpui::{ScrollDelta, ScrollWheelEvent};
1105
1106 use crate::{self as gpui, TestAppContext};
1107
1108 #[gpui::test]
1109 fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
1110 use crate::{
1111 AppContext, Context, Element, IntoElement, ListState, Render, Styled, Window, div,
1112 list, point, px, size,
1113 };
1114
1115 let cx = cx.add_empty_window();
1116
1117 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1118
1119 // Ensure that the list is scrolled to the top
1120 state.scroll_to(gpui::ListOffset {
1121 item_ix: 0,
1122 offset_in_item: px(0.0),
1123 });
1124
1125 struct TestView(ListState);
1126 impl Render for TestView {
1127 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1128 list(self.0.clone(), |_, _, _| {
1129 div().h(px(10.)).w_full().into_any()
1130 })
1131 .w_full()
1132 .h_full()
1133 }
1134 }
1135
1136 // Paint
1137 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1138 cx.new(|_| TestView(state.clone()))
1139 });
1140
1141 // Reset
1142 state.reset(5);
1143
1144 // And then receive a scroll event _before_ the next paint
1145 cx.simulate_event(ScrollWheelEvent {
1146 position: point(px(1.), px(1.)),
1147 delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
1148 ..Default::default()
1149 });
1150
1151 // Scroll position should stay at the top of the list
1152 assert_eq!(state.logical_scroll_top().item_ix, 0);
1153 assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
1154 }
1155
1156 #[gpui::test]
1157 fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
1158 use crate::{
1159 AppContext, Context, Element, IntoElement, ListState, Render, Styled, Window, div,
1160 list, point, px, size,
1161 };
1162
1163 let cx = cx.add_empty_window();
1164
1165 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1166
1167 struct TestView(ListState);
1168 impl Render for TestView {
1169 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1170 list(self.0.clone(), |_, _, _| {
1171 div().h(px(20.)).w_full().into_any()
1172 })
1173 .w_full()
1174 .h_full()
1175 }
1176 }
1177
1178 // Paint
1179 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1180 cx.new(|_| TestView(state.clone()))
1181 });
1182
1183 // Test positive distance: start at item 1, move down 30px
1184 state.scroll_by(px(30.));
1185
1186 // Should move to item 2
1187 let offset = state.logical_scroll_top();
1188 assert_eq!(offset.item_ix, 1);
1189 assert_eq!(offset.offset_in_item, px(10.));
1190
1191 // Test negative distance: start at item 2, move up 30px
1192 state.scroll_by(px(-30.));
1193
1194 // Should move back to item 1
1195 let offset = state.logical_scroll_top();
1196 assert_eq!(offset.item_ix, 0);
1197 assert_eq!(offset.offset_in_item, px(0.));
1198
1199 // Test zero distance
1200 state.scroll_by(px(0.));
1201 let offset = state.logical_scroll_top();
1202 assert_eq!(offset.item_ix, 0);
1203 assert_eq!(offset.offset_in_item, px(0.));
1204 }
1205}