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