gpui/elements/
list.rs

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