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