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    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(&self, height: Pixels, scroll_top: &ListOffset) -> Range<usize> {
530        let mut cursor = self.items.cursor::<ListItemSummary>(());
531        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
532        let start_y = cursor.start().height + scroll_top.offset_in_item;
533        cursor.seek_forward(&Height(start_y + height), Bias::Left);
534        scroll_top.item_ix..cursor.start().count + 1
535    }
536
537    fn scroll(
538        &mut self,
539        scroll_top: &ListOffset,
540        height: Pixels,
541        delta: Point<Pixels>,
542        current_view: EntityId,
543        window: &mut Window,
544        cx: &mut App,
545    ) {
546        // Drop scroll events after a reset, since we can't calculate
547        // the new logical scroll top without the item heights
548        if self.reset {
549            return;
550        }
551
552        let padding = self.last_padding.unwrap_or_default();
553        let scroll_max =
554            (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
555        let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
556            .max(px(0.))
557            .min(scroll_max);
558
559        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
560            self.logical_scroll_top = None;
561        } else {
562            let (start, ..) =
563                self.items
564                    .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
565            let item_ix = start.count;
566            let offset_in_item = new_scroll_top - start.height;
567            self.logical_scroll_top = Some(ListOffset {
568                item_ix,
569                offset_in_item,
570            });
571        }
572
573        if self.scroll_handler.is_some() {
574            let visible_range = self.visible_range(height, scroll_top);
575            self.scroll_handler.as_mut().unwrap()(
576                &ListScrollEvent {
577                    visible_range,
578                    count: self.items.summary().count,
579                    is_scrolled: self.logical_scroll_top.is_some(),
580                },
581                window,
582                cx,
583            );
584        }
585
586        cx.notify(current_view);
587    }
588
589    fn logical_scroll_top(&self) -> ListOffset {
590        self.logical_scroll_top
591            .unwrap_or_else(|| match self.alignment {
592                ListAlignment::Top => ListOffset {
593                    item_ix: 0,
594                    offset_in_item: px(0.),
595                },
596                ListAlignment::Bottom => ListOffset {
597                    item_ix: self.items.summary().count,
598                    offset_in_item: px(0.),
599                },
600            })
601    }
602
603    fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
604        let (start, ..) = self.items.find::<ListItemSummary, _>(
605            (),
606            &Count(logical_scroll_top.item_ix),
607            Bias::Right,
608        );
609        start.height + logical_scroll_top.offset_in_item
610    }
611
612    fn layout_all_items(
613        &mut self,
614        available_width: Pixels,
615        render_item: &mut RenderItemFn,
616        window: &mut Window,
617        cx: &mut App,
618    ) {
619        match &mut self.measuring_behavior {
620            ListMeasuringBehavior::Visible => {
621                return;
622            }
623            ListMeasuringBehavior::Measure(has_measured) => {
624                if *has_measured {
625                    return;
626                }
627                *has_measured = true;
628            }
629        }
630
631        let mut cursor = self.items.cursor::<Count>(());
632        let available_item_space = size(
633            AvailableSpace::Definite(available_width),
634            AvailableSpace::MinContent,
635        );
636
637        let mut measured_items = Vec::default();
638
639        for (ix, item) in cursor.enumerate() {
640            let size = item.size().unwrap_or_else(|| {
641                let mut element = render_item(ix, window, cx);
642                element.layout_as_root(available_item_space, window, cx)
643            });
644
645            measured_items.push(ListItem::Measured {
646                size,
647                focus_handle: item.focus_handle(),
648            });
649        }
650
651        self.items = SumTree::from_iter(measured_items, ());
652    }
653
654    fn layout_items(
655        &mut self,
656        available_width: Option<Pixels>,
657        available_height: Pixels,
658        padding: &Edges<Pixels>,
659        render_item: &mut RenderItemFn,
660        window: &mut Window,
661        cx: &mut App,
662    ) -> LayoutItemsResponse {
663        let old_items = self.items.clone();
664        let mut measured_items = VecDeque::new();
665        let mut item_layouts = VecDeque::new();
666        let mut rendered_height = padding.top;
667        let mut max_item_width = px(0.);
668        let mut scroll_top = self.logical_scroll_top();
669        let mut rendered_focused_item = false;
670
671        let available_item_space = size(
672            available_width.map_or(AvailableSpace::MinContent, |width| {
673                AvailableSpace::Definite(width)
674            }),
675            AvailableSpace::MinContent,
676        );
677
678        let mut cursor = old_items.cursor::<Count>(());
679
680        // Render items after the scroll top, including those in the trailing overdraw
681        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
682        for (ix, item) in cursor.by_ref().enumerate() {
683            let visible_height = rendered_height - scroll_top.offset_in_item;
684            if visible_height >= available_height + self.overdraw {
685                break;
686            }
687
688            // Use the previously cached height and focus handle if available
689            let mut size = item.size();
690
691            // If we're within the visible area or the height wasn't cached, render and measure the item's element
692            if visible_height < available_height || size.is_none() {
693                let item_index = scroll_top.item_ix + ix;
694                let mut element = render_item(item_index, window, cx);
695                let element_size = element.layout_as_root(available_item_space, window, cx);
696                size = Some(element_size);
697
698                // If there's a pending scroll adjustment for the scroll-top
699                // item, apply it, ensuring proportional scroll position is
700                // maintained after re-measuring.
701                if ix == 0 {
702                    if let Some(pending_scroll) = self.pending_scroll.take() {
703                        if pending_scroll.item_ix == scroll_top.item_ix {
704                            scroll_top.offset_in_item =
705                                Pixels(pending_scroll.fraction * element_size.height.0);
706                            self.logical_scroll_top = Some(scroll_top);
707                        }
708                    }
709                }
710
711                if visible_height < available_height {
712                    item_layouts.push_back(ItemLayout {
713                        index: item_index,
714                        element,
715                        size: element_size,
716                    });
717                    if item.contains_focused(window, cx) {
718                        rendered_focused_item = true;
719                    }
720                }
721            }
722
723            let size = size.unwrap();
724            rendered_height += size.height;
725            max_item_width = max_item_width.max(size.width);
726            measured_items.push_back(ListItem::Measured {
727                size,
728                focus_handle: item.focus_handle(),
729            });
730        }
731        rendered_height += padding.bottom;
732
733        // Prepare to start walking upward from the item at the scroll top.
734        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
735
736        // If the rendered items do not fill the visible region, then adjust
737        // the scroll top upward.
738        if rendered_height - scroll_top.offset_in_item < available_height {
739            while rendered_height < available_height {
740                cursor.prev();
741                if let Some(item) = cursor.item() {
742                    let item_index = cursor.start().0;
743                    let mut element = render_item(item_index, window, cx);
744                    let element_size = element.layout_as_root(available_item_space, window, cx);
745                    let focus_handle = item.focus_handle();
746                    rendered_height += element_size.height;
747                    measured_items.push_front(ListItem::Measured {
748                        size: element_size,
749                        focus_handle,
750                    });
751                    item_layouts.push_front(ItemLayout {
752                        index: item_index,
753                        element,
754                        size: element_size,
755                    });
756                    if item.contains_focused(window, cx) {
757                        rendered_focused_item = true;
758                    }
759                } else {
760                    break;
761                }
762            }
763
764            scroll_top = ListOffset {
765                item_ix: cursor.start().0,
766                offset_in_item: rendered_height - available_height,
767            };
768
769            match self.alignment {
770                ListAlignment::Top => {
771                    scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
772                    self.logical_scroll_top = Some(scroll_top);
773                }
774                ListAlignment::Bottom => {
775                    scroll_top = ListOffset {
776                        item_ix: cursor.start().0,
777                        offset_in_item: rendered_height - available_height,
778                    };
779                    self.logical_scroll_top = None;
780                }
781            };
782        }
783
784        // Measure items in the leading overdraw
785        let mut leading_overdraw = scroll_top.offset_in_item;
786        while leading_overdraw < self.overdraw {
787            cursor.prev();
788            if let Some(item) = cursor.item() {
789                let size = if let ListItem::Measured { size, .. } = item {
790                    *size
791                } else {
792                    let mut element = render_item(cursor.start().0, window, cx);
793                    element.layout_as_root(available_item_space, window, cx)
794                };
795
796                leading_overdraw += size.height;
797                measured_items.push_front(ListItem::Measured {
798                    size,
799                    focus_handle: item.focus_handle(),
800                });
801            } else {
802                break;
803            }
804        }
805
806        let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
807        let mut cursor = old_items.cursor::<Count>(());
808        let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right);
809        new_items.extend(measured_items, ());
810        cursor.seek(&Count(measured_range.end), Bias::Right);
811        new_items.append(cursor.suffix(), ());
812        self.items = new_items;
813
814        // If none of the visible items are focused, check if an off-screen item is focused
815        // and include it to be rendered after the visible items so keyboard interaction continues
816        // to work for it.
817        if !rendered_focused_item {
818            let mut cursor = self
819                .items
820                .filter::<_, Count>((), |summary| summary.has_focus_handles);
821            cursor.next();
822            while let Some(item) = cursor.item() {
823                if item.contains_focused(window, cx) {
824                    let item_index = cursor.start().0;
825                    let mut element = render_item(cursor.start().0, window, cx);
826                    let size = element.layout_as_root(available_item_space, window, cx);
827                    item_layouts.push_back(ItemLayout {
828                        index: item_index,
829                        element,
830                        size,
831                    });
832                    break;
833                }
834                cursor.next();
835            }
836        }
837
838        LayoutItemsResponse {
839            max_item_width,
840            scroll_top,
841            item_layouts,
842        }
843    }
844
845    fn prepaint_items(
846        &mut self,
847        bounds: Bounds<Pixels>,
848        padding: Edges<Pixels>,
849        autoscroll: bool,
850        render_item: &mut RenderItemFn,
851        window: &mut Window,
852        cx: &mut App,
853    ) -> Result<LayoutItemsResponse, ListOffset> {
854        window.transact(|window| {
855            match self.measuring_behavior {
856                ListMeasuringBehavior::Measure(has_measured) if !has_measured => {
857                    self.layout_all_items(bounds.size.width, render_item, window, cx);
858                }
859                _ => {}
860            }
861
862            let mut layout_response = self.layout_items(
863                Some(bounds.size.width),
864                bounds.size.height,
865                &padding,
866                render_item,
867                window,
868                cx,
869            );
870
871            // Avoid honoring autoscroll requests from elements other than our children.
872            window.take_autoscroll();
873
874            // Only paint the visible items, if there is actually any space for them (taking padding into account)
875            if bounds.size.height > padding.top + padding.bottom {
876                let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
877                item_origin.y -= layout_response.scroll_top.offset_in_item;
878                for item in &mut layout_response.item_layouts {
879                    window.with_content_mask(Some(ContentMask { bounds }), |window| {
880                        item.element.prepaint_at(item_origin, window, cx);
881                    });
882
883                    if let Some(autoscroll_bounds) = window.take_autoscroll()
884                        && autoscroll
885                    {
886                        if autoscroll_bounds.top() < bounds.top() {
887                            return Err(ListOffset {
888                                item_ix: item.index,
889                                offset_in_item: autoscroll_bounds.top() - item_origin.y,
890                            });
891                        } else if autoscroll_bounds.bottom() > bounds.bottom() {
892                            let mut cursor = self.items.cursor::<Count>(());
893                            cursor.seek(&Count(item.index), Bias::Right);
894                            let mut height = bounds.size.height - padding.top - padding.bottom;
895
896                            // Account for the height of the element down until the autoscroll bottom.
897                            height -= autoscroll_bounds.bottom() - item_origin.y;
898
899                            // Keep decreasing the scroll top until we fill all the available space.
900                            while height > Pixels::ZERO {
901                                cursor.prev();
902                                let Some(item) = cursor.item() else { break };
903
904                                let size = item.size().unwrap_or_else(|| {
905                                    let mut item = render_item(cursor.start().0, window, cx);
906                                    let item_available_size =
907                                        size(bounds.size.width.into(), AvailableSpace::MinContent);
908                                    item.layout_as_root(item_available_size, window, cx)
909                                });
910                                height -= size.height;
911                            }
912
913                            return Err(ListOffset {
914                                item_ix: cursor.start().0,
915                                offset_in_item: if height < Pixels::ZERO {
916                                    -height
917                                } else {
918                                    Pixels::ZERO
919                                },
920                            });
921                        }
922                    }
923
924                    item_origin.y += item.size.height;
925                }
926            } else {
927                layout_response.item_layouts.clear();
928            }
929
930            Ok(layout_response)
931        })
932    }
933
934    // Scrollbar support
935
936    fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
937        let Some(bounds) = self.last_layout_bounds else {
938            return;
939        };
940        let height = bounds.size.height;
941
942        let padding = self.last_padding.unwrap_or_default();
943        let content_height = self.items.summary().height;
944        let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
945        let drag_offset =
946            // if dragging the scrollbar, we want to offset the point if the height changed
947            content_height - self.scrollbar_drag_start_height.unwrap_or(content_height);
948        let new_scroll_top = (point.y - drag_offset).abs().max(px(0.)).min(scroll_max);
949
950        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
951            self.logical_scroll_top = None;
952        } else {
953            let (start, _, _) =
954                self.items
955                    .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
956
957            let item_ix = start.count;
958            let offset_in_item = new_scroll_top - start.height;
959            self.logical_scroll_top = Some(ListOffset {
960                item_ix,
961                offset_in_item,
962            });
963        }
964    }
965}
966
967impl std::fmt::Debug for ListItem {
968    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
969        match self {
970            Self::Unmeasured { .. } => write!(f, "Unrendered"),
971            Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
972        }
973    }
974}
975
976/// An offset into the list's items, in terms of the item index and the number
977/// of pixels off the top left of the item.
978#[derive(Debug, Clone, Copy, Default)]
979pub struct ListOffset {
980    /// The index of an item in the list
981    pub item_ix: usize,
982    /// The number of pixels to offset from the item index.
983    pub offset_in_item: Pixels,
984}
985
986impl Element for List {
987    type RequestLayoutState = ();
988    type PrepaintState = ListPrepaintState;
989
990    fn id(&self) -> Option<crate::ElementId> {
991        None
992    }
993
994    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
995        None
996    }
997
998    fn request_layout(
999        &mut self,
1000        _id: Option<&GlobalElementId>,
1001        _inspector_id: Option<&InspectorElementId>,
1002        window: &mut Window,
1003        cx: &mut App,
1004    ) -> (crate::LayoutId, Self::RequestLayoutState) {
1005        let layout_id = match self.sizing_behavior {
1006            ListSizingBehavior::Infer => {
1007                let mut style = Style::default();
1008                style.overflow.y = Overflow::Scroll;
1009                style.refine(&self.style);
1010                window.with_text_style(style.text_style().cloned(), |window| {
1011                    let state = &mut *self.state.0.borrow_mut();
1012
1013                    let available_height = if let Some(last_bounds) = state.last_layout_bounds {
1014                        last_bounds.size.height
1015                    } else {
1016                        // If we don't have the last layout bounds (first render),
1017                        // we might just use the overdraw value as the available height to layout enough items.
1018                        state.overdraw
1019                    };
1020                    let padding = style.padding.to_pixels(
1021                        state.last_layout_bounds.unwrap_or_default().size.into(),
1022                        window.rem_size(),
1023                    );
1024
1025                    let layout_response = state.layout_items(
1026                        None,
1027                        available_height,
1028                        &padding,
1029                        &mut self.render_item,
1030                        window,
1031                        cx,
1032                    );
1033                    let max_element_width = layout_response.max_item_width;
1034
1035                    let summary = state.items.summary();
1036                    let total_height = summary.height;
1037
1038                    window.request_measured_layout(
1039                        style,
1040                        move |known_dimensions, available_space, _window, _cx| {
1041                            let width =
1042                                known_dimensions
1043                                    .width
1044                                    .unwrap_or(match available_space.width {
1045                                        AvailableSpace::Definite(x) => x,
1046                                        AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1047                                            max_element_width
1048                                        }
1049                                    });
1050                            let height = match available_space.height {
1051                                AvailableSpace::Definite(height) => total_height.min(height),
1052                                AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1053                                    total_height
1054                                }
1055                            };
1056                            size(width, height)
1057                        },
1058                    )
1059                })
1060            }
1061            ListSizingBehavior::Auto => {
1062                let mut style = Style::default();
1063                style.refine(&self.style);
1064                window.with_text_style(style.text_style().cloned(), |window| {
1065                    window.request_layout(style, None, cx)
1066                })
1067            }
1068        };
1069        (layout_id, ())
1070    }
1071
1072    fn prepaint(
1073        &mut self,
1074        _id: Option<&GlobalElementId>,
1075        _inspector_id: Option<&InspectorElementId>,
1076        bounds: Bounds<Pixels>,
1077        _: &mut Self::RequestLayoutState,
1078        window: &mut Window,
1079        cx: &mut App,
1080    ) -> ListPrepaintState {
1081        let state = &mut *self.state.0.borrow_mut();
1082        state.reset = false;
1083
1084        let mut style = Style::default();
1085        style.refine(&self.style);
1086
1087        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1088
1089        // If the width of the list has changed, invalidate all cached item heights
1090        if state
1091            .last_layout_bounds
1092            .is_none_or(|last_bounds| last_bounds.size.width != bounds.size.width)
1093        {
1094            let new_items = SumTree::from_iter(
1095                state.items.iter().map(|item| ListItem::Unmeasured {
1096                    focus_handle: item.focus_handle(),
1097                }),
1098                (),
1099            );
1100
1101            state.items = new_items;
1102        }
1103
1104        let padding = style
1105            .padding
1106            .to_pixels(bounds.size.into(), window.rem_size());
1107        let layout =
1108            match state.prepaint_items(bounds, padding, true, &mut self.render_item, window, cx) {
1109                Ok(layout) => layout,
1110                Err(autoscroll_request) => {
1111                    state.logical_scroll_top = Some(autoscroll_request);
1112                    state
1113                        .prepaint_items(bounds, padding, false, &mut self.render_item, window, cx)
1114                        .unwrap()
1115                }
1116            };
1117
1118        state.last_layout_bounds = Some(bounds);
1119        state.last_padding = Some(padding);
1120        ListPrepaintState { hitbox, layout }
1121    }
1122
1123    fn paint(
1124        &mut self,
1125        _id: Option<&GlobalElementId>,
1126        _inspector_id: Option<&InspectorElementId>,
1127        bounds: Bounds<crate::Pixels>,
1128        _: &mut Self::RequestLayoutState,
1129        prepaint: &mut Self::PrepaintState,
1130        window: &mut Window,
1131        cx: &mut App,
1132    ) {
1133        let current_view = window.current_view();
1134        window.with_content_mask(Some(ContentMask { bounds }), |window| {
1135            for item in &mut prepaint.layout.item_layouts {
1136                item.element.paint(window, cx);
1137            }
1138        });
1139
1140        let list_state = self.state.clone();
1141        let height = bounds.size.height;
1142        let scroll_top = prepaint.layout.scroll_top;
1143        let hitbox_id = prepaint.hitbox.id;
1144        let mut accumulated_scroll_delta = ScrollDelta::default();
1145        window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
1146            if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
1147                accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
1148                let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1149                list_state.0.borrow_mut().scroll(
1150                    &scroll_top,
1151                    height,
1152                    pixel_delta,
1153                    current_view,
1154                    window,
1155                    cx,
1156                )
1157            }
1158        });
1159    }
1160}
1161
1162impl IntoElement for List {
1163    type Element = Self;
1164
1165    fn into_element(self) -> Self::Element {
1166        self
1167    }
1168}
1169
1170impl Styled for List {
1171    fn style(&mut self) -> &mut StyleRefinement {
1172        &mut self.style
1173    }
1174}
1175
1176impl sum_tree::Item for ListItem {
1177    type Summary = ListItemSummary;
1178
1179    fn summary(&self, _: ()) -> Self::Summary {
1180        match self {
1181            ListItem::Unmeasured { focus_handle } => ListItemSummary {
1182                count: 1,
1183                rendered_count: 0,
1184                unrendered_count: 1,
1185                height: px(0.),
1186                has_focus_handles: focus_handle.is_some(),
1187            },
1188            ListItem::Measured {
1189                size, focus_handle, ..
1190            } => ListItemSummary {
1191                count: 1,
1192                rendered_count: 1,
1193                unrendered_count: 0,
1194                height: size.height,
1195                has_focus_handles: focus_handle.is_some(),
1196            },
1197        }
1198    }
1199}
1200
1201impl sum_tree::ContextLessSummary for ListItemSummary {
1202    fn zero() -> Self {
1203        Default::default()
1204    }
1205
1206    fn add_summary(&mut self, summary: &Self) {
1207        self.count += summary.count;
1208        self.rendered_count += summary.rendered_count;
1209        self.unrendered_count += summary.unrendered_count;
1210        self.height += summary.height;
1211        self.has_focus_handles |= summary.has_focus_handles;
1212    }
1213}
1214
1215impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1216    fn zero(_cx: ()) -> Self {
1217        Default::default()
1218    }
1219
1220    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1221        self.0 += summary.count;
1222    }
1223}
1224
1225impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1226    fn zero(_cx: ()) -> Self {
1227        Default::default()
1228    }
1229
1230    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1231        self.0 += summary.height;
1232    }
1233}
1234
1235impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1236    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1237        self.0.partial_cmp(&other.count).unwrap()
1238    }
1239}
1240
1241impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1242    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1243        self.0.partial_cmp(&other.height).unwrap()
1244    }
1245}
1246
1247#[cfg(test)]
1248mod test {
1249
1250    use gpui::{ScrollDelta, ScrollWheelEvent};
1251    use std::cell::Cell;
1252    use std::rc::Rc;
1253
1254    use crate::{
1255        self as gpui, AppContext, Context, Element, IntoElement, ListState, Render, Styled,
1256        TestAppContext, Window, div, list, point, px, size,
1257    };
1258
1259    #[gpui::test]
1260    fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
1261        let cx = cx.add_empty_window();
1262
1263        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1264
1265        // Ensure that the list is scrolled to the top
1266        state.scroll_to(gpui::ListOffset {
1267            item_ix: 0,
1268            offset_in_item: px(0.0),
1269        });
1270
1271        struct TestView(ListState);
1272        impl Render for TestView {
1273            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1274                list(self.0.clone(), |_, _, _| {
1275                    div().h(px(10.)).w_full().into_any()
1276                })
1277                .w_full()
1278                .h_full()
1279            }
1280        }
1281
1282        // Paint
1283        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1284            cx.new(|_| TestView(state.clone()))
1285        });
1286
1287        // Reset
1288        state.reset(5);
1289
1290        // And then receive a scroll event _before_ the next paint
1291        cx.simulate_event(ScrollWheelEvent {
1292            position: point(px(1.), px(1.)),
1293            delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
1294            ..Default::default()
1295        });
1296
1297        // Scroll position should stay at the top of the list
1298        assert_eq!(state.logical_scroll_top().item_ix, 0);
1299        assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
1300    }
1301
1302    #[gpui::test]
1303    fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
1304        let cx = cx.add_empty_window();
1305
1306        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1307
1308        struct TestView(ListState);
1309        impl Render for TestView {
1310            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1311                list(self.0.clone(), |_, _, _| {
1312                    div().h(px(20.)).w_full().into_any()
1313                })
1314                .w_full()
1315                .h_full()
1316            }
1317        }
1318
1319        // Paint
1320        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1321            cx.new(|_| TestView(state.clone()))
1322        });
1323
1324        // Test positive distance: start at item 1, move down 30px
1325        state.scroll_by(px(30.));
1326
1327        // Should move to item 2
1328        let offset = state.logical_scroll_top();
1329        assert_eq!(offset.item_ix, 1);
1330        assert_eq!(offset.offset_in_item, px(10.));
1331
1332        // Test negative distance: start at item 2, move up 30px
1333        state.scroll_by(px(-30.));
1334
1335        // Should move back to item 1
1336        let offset = state.logical_scroll_top();
1337        assert_eq!(offset.item_ix, 0);
1338        assert_eq!(offset.offset_in_item, px(0.));
1339
1340        // Test zero distance
1341        state.scroll_by(px(0.));
1342        let offset = state.logical_scroll_top();
1343        assert_eq!(offset.item_ix, 0);
1344        assert_eq!(offset.offset_in_item, px(0.));
1345    }
1346
1347    #[gpui::test]
1348    fn test_remeasure(cx: &mut TestAppContext) {
1349        let cx = cx.add_empty_window();
1350
1351        // Create a list with 10 items, each 100px tall. We'll keep a reference
1352        // to the item height so we can later change the height and assert how
1353        // `ListState` handles it.
1354        let item_height = Rc::new(Cell::new(100usize));
1355        let state = ListState::new(10, crate::ListAlignment::Top, px(10.));
1356
1357        struct TestView {
1358            state: ListState,
1359            item_height: Rc<Cell<usize>>,
1360        }
1361
1362        impl Render for TestView {
1363            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1364                let height = self.item_height.get();
1365                list(self.state.clone(), move |_, _, _| {
1366                    div().h(px(height as f32)).w_full().into_any()
1367                })
1368                .w_full()
1369                .h_full()
1370            }
1371        }
1372
1373        let state_clone = state.clone();
1374        let item_height_clone = item_height.clone();
1375        let view = cx.update(|_, cx| {
1376            cx.new(|_| TestView {
1377                state: state_clone,
1378                item_height: item_height_clone,
1379            })
1380        });
1381
1382        // Simulate scrolling 40px inside the element with index 2. Since the
1383        // original item height is 100px, this equates to 40% inside the item.
1384        state.scroll_to(gpui::ListOffset {
1385            item_ix: 2,
1386            offset_in_item: px(40.),
1387        });
1388
1389        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1390            view.clone()
1391        });
1392
1393        let offset = state.logical_scroll_top();
1394        assert_eq!(offset.item_ix, 2);
1395        assert_eq!(offset.offset_in_item, px(40.));
1396
1397        // Update the `item_height` to be 50px instead of 100px so we can assert
1398        // that the scroll position is proportionally preserved, that is,
1399        // instead of 40px from the top of item 2, it should be 20px, since the
1400        // item's height has been halved.
1401        item_height.set(50);
1402        state.remeasure();
1403
1404        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| view);
1405
1406        let offset = state.logical_scroll_top();
1407        assert_eq!(offset.item_ix, 2);
1408        assert_eq!(offset.offset_in_item, px(20.));
1409    }
1410}