Skip to main content

boltz_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    follow_state: FollowState,
76}
77
78/// Keeps track of a fractional scroll position within an item for restoration
79/// after remeasurement.
80struct PendingScrollFraction {
81    /// The index of the item to scroll within.
82    item_ix: usize,
83    /// Fractional offset (0.0 to 1.0) within the item's height.
84    fraction: f32,
85}
86
87/// Controls whether the list automatically follows new content at the end.
88#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
89pub enum FollowMode {
90    /// Normal scrolling — no automatic following.
91    #[default]
92    Normal,
93    /// The list should auto-scroll along with the tail, when scrolled to bottom.
94    Tail,
95}
96
97#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
98enum FollowState {
99    #[default]
100    Normal,
101    Tail {
102        is_following: bool,
103    },
104}
105
106impl FollowState {
107    fn is_following(&self) -> bool {
108        matches!(self, FollowState::Tail { is_following: true })
109    }
110
111    fn has_stopped_following(&self) -> bool {
112        matches!(
113            self,
114            FollowState::Tail {
115                is_following: false
116            }
117        )
118    }
119
120    fn start_following(&mut self) {
121        if let FollowState::Tail {
122            is_following: false,
123        } = self
124        {
125            *self = FollowState::Tail { is_following: true };
126        }
127    }
128
129    fn stop_following(&mut self) {
130        if let FollowState::Tail { is_following: true } = self {
131            *self = FollowState::Tail {
132                is_following: false,
133            };
134        }
135    }
136}
137
138/// Whether the list is scrolling from top to bottom or bottom to top.
139#[derive(Clone, Copy, Debug, Eq, PartialEq)]
140pub enum ListAlignment {
141    /// The list is scrolling from top to bottom, like most lists.
142    Top,
143    /// The list is scrolling from bottom to top, like a chat log.
144    Bottom,
145}
146
147/// A scroll event that has been converted to be in terms of the list's items.
148pub struct ListScrollEvent {
149    /// The range of items currently visible in the list, after applying the scroll event.
150    pub visible_range: Range<usize>,
151
152    /// The number of items that are currently visible in the list, after applying the scroll event.
153    pub count: usize,
154
155    /// Whether the list has been scrolled.
156    pub is_scrolled: bool,
157
158    /// Whether the list is currently in follow-tail mode (auto-scrolling to end).
159    pub is_following_tail: bool,
160}
161
162/// The sizing behavior to apply during layout.
163#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
164pub enum ListSizingBehavior {
165    /// The list should calculate its size based on the size of its items.
166    Infer,
167    /// The list should not calculate a fixed size.
168    #[default]
169    Auto,
170}
171
172/// The measuring behavior to apply during layout.
173#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
174pub enum ListMeasuringBehavior {
175    /// Measure all items in the list.
176    /// Note: This can be expensive for the first frame in a large list.
177    Measure(bool),
178    /// Only measure visible items
179    #[default]
180    Visible,
181}
182
183impl ListMeasuringBehavior {
184    fn reset(&mut self) {
185        match self {
186            ListMeasuringBehavior::Measure(has_measured) => *has_measured = false,
187            ListMeasuringBehavior::Visible => {}
188        }
189    }
190}
191
192/// The horizontal sizing behavior to apply during layout.
193#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
194pub enum ListHorizontalSizingBehavior {
195    /// List items' width can never exceed the width of the list.
196    #[default]
197    FitList,
198    /// List items' width may go over the width of the list, if any item is wider.
199    Unconstrained,
200}
201
202struct LayoutItemsResponse {
203    max_item_width: Pixels,
204    scroll_top: ListOffset,
205    item_layouts: VecDeque<ItemLayout>,
206}
207
208struct ItemLayout {
209    index: usize,
210    element: AnyElement,
211    size: Size<Pixels>,
212}
213
214/// Frame state used by the [List] element after layout.
215pub struct ListPrepaintState {
216    hitbox: Hitbox,
217    layout: LayoutItemsResponse,
218}
219
220#[derive(Clone)]
221enum ListItem {
222    Unmeasured {
223        size_hint: Option<Size<Pixels>>,
224        focus_handle: Option<FocusHandle>,
225    },
226    Measured {
227        size: Size<Pixels>,
228        focus_handle: Option<FocusHandle>,
229    },
230}
231
232impl ListItem {
233    fn size(&self) -> Option<Size<Pixels>> {
234        if let ListItem::Measured { size, .. } = self {
235            Some(*size)
236        } else {
237            None
238        }
239    }
240
241    fn size_hint(&self) -> Option<Size<Pixels>> {
242        match self {
243            ListItem::Measured { size, .. } => Some(*size),
244            ListItem::Unmeasured { size_hint, .. } => *size_hint,
245        }
246    }
247
248    fn focus_handle(&self) -> Option<FocusHandle> {
249        match self {
250            ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
251                focus_handle.clone()
252            }
253        }
254    }
255
256    fn contains_focused(&self, window: &Window, cx: &App) -> bool {
257        match self {
258            ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
259                focus_handle
260                    .as_ref()
261                    .is_some_and(|handle| handle.contains_focused(window, cx))
262            }
263        }
264    }
265}
266
267#[derive(Clone, Debug, Default, PartialEq)]
268struct ListItemSummary {
269    count: usize,
270    rendered_count: usize,
271    unrendered_count: usize,
272    height: Pixels,
273    has_focus_handles: bool,
274}
275
276#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
277struct Count(usize);
278
279#[derive(Clone, Debug, Default)]
280struct Height(Pixels);
281
282impl ListState {
283    /// Construct a new list state, for storage on a view.
284    ///
285    /// The overdraw parameter controls how much extra space is rendered
286    /// above and below the visible area. Elements within this area will
287    /// be measured even though they are not visible. This can help ensure
288    /// that the list doesn't flicker or pop in when scrolling.
289    pub fn new(item_count: usize, alignment: ListAlignment, overdraw: Pixels) -> Self {
290        let this = Self(Rc::new(RefCell::new(StateInner {
291            last_layout_bounds: None,
292            last_padding: None,
293            items: SumTree::default(),
294            logical_scroll_top: None,
295            alignment,
296            overdraw,
297            scroll_handler: None,
298            reset: false,
299            scrollbar_drag_start_height: None,
300            measuring_behavior: ListMeasuringBehavior::default(),
301            pending_scroll: None,
302            follow_state: FollowState::default(),
303        })));
304        this.splice(0..0, item_count);
305        this
306    }
307
308    /// Set the list to measure all items in the list in the first layout phase.
309    ///
310    /// This is useful for ensuring that the scrollbar size is correct instead of based on only rendered elements.
311    pub fn measure_all(self) -> Self {
312        self.0.borrow_mut().measuring_behavior = ListMeasuringBehavior::Measure(false);
313        self
314    }
315
316    /// Reset this instantiation of the list state.
317    ///
318    /// Note that this will cause scroll events to be dropped until the next paint.
319    pub fn reset(&self, element_count: usize) {
320        let old_count = {
321            let state = &mut *self.0.borrow_mut();
322            state.reset = true;
323            state.measuring_behavior.reset();
324            state.logical_scroll_top = None;
325            state.scrollbar_drag_start_height = None;
326            state.items.summary().count
327        };
328
329        self.splice(0..old_count, element_count);
330    }
331
332    /// Remeasure all items while preserving proportional scroll position.
333    ///
334    /// Use this when item heights may have changed (e.g., font size changes)
335    /// but the number and identity of items remains the same.
336    pub fn remeasure(&self) {
337        let count = self.item_count();
338        self.remeasure_items(0..count);
339    }
340
341    /// Mark items in `range` as needing remeasurement while preserving
342    /// the current scroll position. Unlike [`Self::splice`], this does
343    /// not change the number of items or blow away `logical_scroll_top`.
344    ///
345    /// Use this when an item's content has changed and its rendered
346    /// height may be different (e.g., streaming text, tool results
347    /// loading), but the item itself still exists at the same index.
348    pub fn remeasure_items(&self, range: Range<usize>) {
349        let state = &mut *self.0.borrow_mut();
350
351        // If the scroll-top item falls within the remeasured range,
352        // store a fractional offset so the layout can restore the
353        // proportional scroll position after the item is re-rendered
354        // at its new height.
355        if let Some(scroll_top) = state.logical_scroll_top {
356            if range.contains(&scroll_top.item_ix) {
357                let mut cursor = state.items.cursor::<Count>(());
358                cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
359
360                if let Some(item) = cursor.item() {
361                    if let Some(size) = item.size() {
362                        let fraction = if size.height.0 > 0.0 {
363                            (scroll_top.offset_in_item.0 / size.height.0).clamp(0.0, 1.0)
364                        } else {
365                            0.0
366                        };
367
368                        state.pending_scroll = Some(PendingScrollFraction {
369                            item_ix: scroll_top.item_ix,
370                            fraction,
371                        });
372                    }
373                }
374            }
375        }
376
377        // Rebuild the tree, replacing items in the range with
378        // Unmeasured copies that keep their focus handles.
379        let new_items = {
380            let mut cursor = state.items.cursor::<Count>(());
381            let mut new_items = cursor.slice(&Count(range.start), Bias::Right);
382            let invalidated = cursor.slice(&Count(range.end), Bias::Right);
383            new_items.extend(
384                invalidated.iter().map(|item| ListItem::Unmeasured {
385                    size_hint: item.size_hint(),
386                    focus_handle: item.focus_handle(),
387                }),
388                (),
389            );
390            new_items.append(cursor.suffix(), ());
391            new_items
392        };
393        state.items = new_items;
394        state.measuring_behavior.reset();
395    }
396
397    /// The number of items in this list.
398    pub fn item_count(&self) -> usize {
399        self.0.borrow().items.summary().count
400    }
401
402    /// Inform the list state that the items in `old_range` have been replaced
403    /// by `count` new items that must be recalculated.
404    pub fn splice(&self, old_range: Range<usize>, count: usize) {
405        self.splice_focusable(old_range, (0..count).map(|_| None))
406    }
407
408    /// Register with the list state that the items in `old_range` have been replaced
409    /// by new items. As opposed to [`Self::splice`], this method allows an iterator of optional focus handles
410    /// to be supplied to properly integrate with items in the list that can be focused. If a focused item
411    /// is scrolled out of view, the list will continue to render it to allow keyboard interaction.
412    pub fn splice_focusable(
413        &self,
414        old_range: Range<usize>,
415        focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
416    ) {
417        let state = &mut *self.0.borrow_mut();
418
419        let mut old_items = state.items.cursor::<Count>(());
420        let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right);
421        old_items.seek_forward(&Count(old_range.end), Bias::Right);
422
423        let mut spliced_count = 0;
424        new_items.extend(
425            focus_handles.into_iter().map(|focus_handle| {
426                spliced_count += 1;
427                ListItem::Unmeasured {
428                    size_hint: None,
429                    focus_handle,
430                }
431            }),
432            (),
433        );
434        new_items.append(old_items.suffix(), ());
435        drop(old_items);
436        state.items = new_items;
437
438        if let Some(ListOffset {
439            item_ix,
440            offset_in_item,
441        }) = state.logical_scroll_top.as_mut()
442        {
443            if old_range.contains(item_ix) {
444                *item_ix = old_range.start;
445                *offset_in_item = px(0.);
446            } else if old_range.end <= *item_ix {
447                *item_ix = *item_ix - (old_range.end - old_range.start) + spliced_count;
448            }
449        }
450    }
451
452    /// Set a handler that will be called when the list is scrolled.
453    pub fn set_scroll_handler(
454        &self,
455        handler: impl FnMut(&ListScrollEvent, &mut Window, &mut App) + 'static,
456    ) {
457        self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
458    }
459
460    /// Get the current scroll offset, in terms of the list's items.
461    pub fn logical_scroll_top(&self) -> ListOffset {
462        self.0.borrow().logical_scroll_top()
463    }
464
465    /// Scroll the list by the given offset
466    pub fn scroll_by(&self, distance: Pixels) {
467        if distance == px(0.) {
468            return;
469        }
470
471        let current_offset = self.logical_scroll_top();
472        let state = &mut *self.0.borrow_mut();
473
474        if distance < px(0.) {
475            state.follow_state.stop_following();
476        }
477
478        let mut cursor = state.items.cursor::<ListItemSummary>(());
479        cursor.seek(&Count(current_offset.item_ix), Bias::Right);
480
481        let start_pixel_offset = cursor.start().height + current_offset.offset_in_item;
482        let new_pixel_offset = (start_pixel_offset + distance).max(px(0.));
483        if new_pixel_offset > start_pixel_offset {
484            cursor.seek_forward(&Height(new_pixel_offset), Bias::Right);
485        } else {
486            cursor.seek(&Height(new_pixel_offset), Bias::Right);
487        }
488
489        state.logical_scroll_top = Some(ListOffset {
490            item_ix: cursor.start().count,
491            offset_in_item: new_pixel_offset - cursor.start().height,
492        });
493    }
494
495    /// Scroll the list to the very end (past the last item).
496    ///
497    /// Unlike [`scroll_to_reveal_item`], this uses the total item count as the
498    /// anchor, so the list's layout pass will walk backwards from the end and
499    /// always show the bottom of the last item — even when that item is still
500    /// growing (e.g. during streaming).
501    pub fn scroll_to_end(&self) {
502        let state = &mut *self.0.borrow_mut();
503        let item_count = state.items.summary().count;
504        state.logical_scroll_top = Some(ListOffset {
505            item_ix: item_count,
506            offset_in_item: px(0.),
507        });
508    }
509
510    /// Set the follow mode for the list. In `Tail` mode, the list
511    /// will auto-scroll to the end and re-engage after the user
512    /// scrolls back to the bottom. In `Normal` mode, no automatic
513    /// following occurs.
514    pub fn set_follow_mode(&self, mode: FollowMode) {
515        let state = &mut *self.0.borrow_mut();
516
517        match mode {
518            FollowMode::Normal => {
519                state.follow_state = FollowState::Normal;
520            }
521            FollowMode::Tail => {
522                state.follow_state = FollowState::Tail { is_following: true };
523                if matches!(mode, FollowMode::Tail) {
524                    let item_count = state.items.summary().count;
525                    state.logical_scroll_top = Some(ListOffset {
526                        item_ix: item_count,
527                        offset_in_item: px(0.),
528                    });
529                }
530            }
531        }
532    }
533
534    /// Returns whether the list is currently actively following the
535    /// tail (snapping to the end on each layout).
536    pub fn is_following_tail(&self) -> bool {
537        matches!(
538            self.0.borrow().follow_state,
539            FollowState::Tail { is_following: true }
540        )
541    }
542
543    /// Scroll the list to the given offset
544    pub fn scroll_to(&self, mut scroll_top: ListOffset) {
545        let state = &mut *self.0.borrow_mut();
546        let item_count = state.items.summary().count;
547        if scroll_top.item_ix >= item_count {
548            scroll_top.item_ix = item_count;
549            scroll_top.offset_in_item = px(0.);
550        }
551
552        if scroll_top.item_ix < item_count {
553            state.follow_state.stop_following();
554        }
555
556        state.logical_scroll_top = Some(scroll_top);
557    }
558
559    /// Scroll the list to the given item, such that the item is fully visible.
560    pub fn scroll_to_reveal_item(&self, ix: usize) {
561        let state = &mut *self.0.borrow_mut();
562
563        let mut scroll_top = state.logical_scroll_top();
564        let height = state
565            .last_layout_bounds
566            .map_or(px(0.), |bounds| bounds.size.height);
567        let padding = state.last_padding.unwrap_or_default();
568
569        if ix <= scroll_top.item_ix {
570            scroll_top.item_ix = ix;
571            scroll_top.offset_in_item = px(0.);
572        } else {
573            let mut cursor = state.items.cursor::<ListItemSummary>(());
574            cursor.seek(&Count(ix + 1), Bias::Right);
575            let bottom = cursor.start().height + padding.top;
576            let goal_top = px(0.).max(bottom - height + padding.bottom);
577
578            cursor.seek(&Height(goal_top), Bias::Left);
579            let start_ix = cursor.start().count;
580            let start_item_top = cursor.start().height;
581
582            if start_ix >= scroll_top.item_ix {
583                scroll_top.item_ix = start_ix;
584                scroll_top.offset_in_item = goal_top - start_item_top;
585            }
586        }
587
588        state.logical_scroll_top = Some(scroll_top);
589    }
590
591    /// Get the bounds for the given item in window coordinates, if it's
592    /// been rendered.
593    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
594        let state = &*self.0.borrow();
595
596        let bounds = state.last_layout_bounds.unwrap_or_default();
597        let scroll_top = state.logical_scroll_top();
598        if ix < scroll_top.item_ix {
599            return None;
600        }
601
602        let mut cursor = state.items.cursor::<Dimensions<Count, Height>>(());
603        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
604
605        let scroll_top = cursor.start().1.0 + scroll_top.offset_in_item;
606
607        cursor.seek_forward(&Count(ix), Bias::Right);
608        if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
609            let &Dimensions(Count(count), Height(top), _) = cursor.start();
610            if count == ix {
611                let top = bounds.top() + top - scroll_top;
612                return Some(Bounds::from_corners(
613                    point(bounds.left(), top),
614                    point(bounds.right(), top + size.height),
615                ));
616            }
617        }
618        None
619    }
620
621    /// Call this method when the user starts dragging the scrollbar.
622    ///
623    /// This will prevent the height reported to the scrollbar from changing during the drag
624    /// as items in the overdraw get measured, and help offset scroll position changes accordingly.
625    pub fn scrollbar_drag_started(&self) {
626        let mut state = self.0.borrow_mut();
627        state.scrollbar_drag_start_height = Some(state.items.summary().height);
628    }
629
630    /// Called when the user stops dragging the scrollbar.
631    ///
632    /// See `scrollbar_drag_started`.
633    pub fn scrollbar_drag_ended(&self) {
634        self.0.borrow_mut().scrollbar_drag_start_height.take();
635    }
636
637    /// Set the offset from the scrollbar
638    pub fn set_offset_from_scrollbar(&self, point: Point<Pixels>) {
639        self.0.borrow_mut().set_offset_from_scrollbar(point);
640    }
641
642    /// Returns the maximum scroll offset according to the items we have measured.
643    /// This value remains constant while dragging to prevent the scrollbar from moving away unexpectedly.
644    pub fn max_offset_for_scrollbar(&self) -> Point<Pixels> {
645        let state = self.0.borrow();
646        point(Pixels::ZERO, state.max_scroll_offset())
647    }
648
649    /// Returns the current scroll offset adjusted for the scrollbar
650    pub fn scroll_px_offset_for_scrollbar(&self) -> Point<Pixels> {
651        let state = &self.0.borrow();
652
653        if state.logical_scroll_top.is_none() && state.alignment == ListAlignment::Bottom {
654            return Point::new(px(0.), -state.max_scroll_offset());
655        }
656
657        let logical_scroll_top = state.logical_scroll_top();
658
659        let mut cursor = state.items.cursor::<ListItemSummary>(());
660        let summary: ListItemSummary =
661            cursor.summary(&Count(logical_scroll_top.item_ix), Bias::Right);
662        let content_height = state.items.summary().height;
663        let drag_offset =
664            // if dragging the scrollbar, we want to offset the point if the height changed
665            content_height - state.scrollbar_drag_start_height.unwrap_or(content_height);
666        let offset = summary.height + logical_scroll_top.offset_in_item - drag_offset;
667
668        Point::new(px(0.), -offset)
669    }
670
671    /// Return the bounds of the viewport in pixels.
672    pub fn viewport_bounds(&self) -> Bounds<Pixels> {
673        self.0.borrow().last_layout_bounds.unwrap_or_default()
674    }
675}
676
677impl StateInner {
678    fn max_scroll_offset(&self) -> Pixels {
679        let bounds = self.last_layout_bounds.unwrap_or_default();
680        let height = self
681            .scrollbar_drag_start_height
682            .unwrap_or_else(|| self.items.summary().height);
683        (height - bounds.size.height).max(px(0.))
684    }
685
686    fn visible_range(
687        items: &SumTree<ListItem>,
688        height: Pixels,
689        scroll_top: &ListOffset,
690    ) -> Range<usize> {
691        let mut cursor = items.cursor::<ListItemSummary>(());
692        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
693        let start_y = cursor.start().height + scroll_top.offset_in_item;
694        cursor.seek_forward(&Height(start_y + height), Bias::Left);
695        scroll_top.item_ix..cursor.start().count + 1
696    }
697
698    fn scroll(
699        &mut self,
700        scroll_top: &ListOffset,
701        height: Pixels,
702        delta: Point<Pixels>,
703        current_view: EntityId,
704        window: &mut Window,
705        cx: &mut App,
706    ) {
707        // Drop scroll events after a reset, since we can't calculate
708        // the new logical scroll top without the item heights
709        if self.reset {
710            return;
711        }
712
713        let padding = self.last_padding.unwrap_or_default();
714        let scroll_max =
715            (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
716        let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
717            .max(px(0.))
718            .min(scroll_max);
719
720        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
721            self.logical_scroll_top = None;
722        } else {
723            let (start, ..) =
724                self.items
725                    .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
726            let item_ix = start.count;
727            let offset_in_item = new_scroll_top - start.height;
728            self.logical_scroll_top = Some(ListOffset {
729                item_ix,
730                offset_in_item,
731            });
732        }
733
734        if delta.y > px(0.) {
735            self.follow_state.stop_following();
736        }
737
738        if let Some(handler) = self.scroll_handler.as_mut() {
739            let visible_range = Self::visible_range(&self.items, height, scroll_top);
740            handler(
741                &ListScrollEvent {
742                    visible_range,
743                    count: self.items.summary().count,
744                    is_scrolled: self.logical_scroll_top.is_some(),
745                    is_following_tail: matches!(
746                        self.follow_state,
747                        FollowState::Tail { is_following: true }
748                    ),
749                },
750                window,
751                cx,
752            );
753        }
754
755        cx.notify(current_view);
756    }
757
758    fn logical_scroll_top(&self) -> ListOffset {
759        self.logical_scroll_top
760            .unwrap_or_else(|| match self.alignment {
761                ListAlignment::Top => ListOffset {
762                    item_ix: 0,
763                    offset_in_item: px(0.),
764                },
765                ListAlignment::Bottom => ListOffset {
766                    item_ix: self.items.summary().count,
767                    offset_in_item: px(0.),
768                },
769            })
770    }
771
772    fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
773        let (start, ..) = self.items.find::<ListItemSummary, _>(
774            (),
775            &Count(logical_scroll_top.item_ix),
776            Bias::Right,
777        );
778        start.height + logical_scroll_top.offset_in_item
779    }
780
781    fn layout_all_items(
782        &mut self,
783        available_width: Pixels,
784        render_item: &mut RenderItemFn,
785        window: &mut Window,
786        cx: &mut App,
787    ) {
788        match &mut self.measuring_behavior {
789            ListMeasuringBehavior::Visible => {
790                return;
791            }
792            ListMeasuringBehavior::Measure(has_measured) => {
793                if *has_measured {
794                    return;
795                }
796                *has_measured = true;
797            }
798        }
799
800        let mut cursor = self.items.cursor::<Count>(());
801        let available_item_space = size(
802            AvailableSpace::Definite(available_width),
803            AvailableSpace::MinContent,
804        );
805
806        let mut measured_items = Vec::default();
807
808        for (ix, item) in cursor.enumerate() {
809            let size = item.size().unwrap_or_else(|| {
810                let mut element = render_item(ix, window, cx);
811                element.layout_as_root(available_item_space, window, cx)
812            });
813
814            measured_items.push(ListItem::Measured {
815                size,
816                focus_handle: item.focus_handle(),
817            });
818        }
819
820        self.items = SumTree::from_iter(measured_items, ());
821    }
822
823    fn layout_items(
824        &mut self,
825        available_width: Option<Pixels>,
826        available_height: Pixels,
827        padding: &Edges<Pixels>,
828        render_item: &mut RenderItemFn,
829        window: &mut Window,
830        cx: &mut App,
831    ) -> LayoutItemsResponse {
832        let old_items = self.items.clone();
833        let mut measured_items = VecDeque::new();
834        let mut item_layouts = VecDeque::new();
835        let mut rendered_height = padding.top;
836        let mut max_item_width = px(0.);
837        let mut scroll_top = self.logical_scroll_top();
838
839        if self.follow_state.is_following() {
840            scroll_top = ListOffset {
841                item_ix: self.items.summary().count,
842                offset_in_item: px(0.),
843            };
844            self.logical_scroll_top = Some(scroll_top);
845        }
846
847        let mut rendered_focused_item = false;
848
849        let available_item_space = size(
850            available_width.map_or(AvailableSpace::MinContent, |width| {
851                AvailableSpace::Definite(width)
852            }),
853            AvailableSpace::MinContent,
854        );
855
856        let mut cursor = old_items.cursor::<Count>(());
857
858        // Render items after the scroll top, including those in the trailing overdraw
859        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
860        for (ix, item) in cursor.by_ref().enumerate() {
861            let visible_height = rendered_height - scroll_top.offset_in_item;
862            if visible_height >= available_height + self.overdraw {
863                break;
864            }
865
866            // Use the previously cached height and focus handle if available
867            let mut size = item.size();
868
869            // If we're within the visible area or the height wasn't cached, render and measure the item's element
870            if visible_height < available_height || size.is_none() {
871                let item_index = scroll_top.item_ix + ix;
872                let mut element = render_item(item_index, window, cx);
873                let element_size = element.layout_as_root(available_item_space, window, cx);
874                size = Some(element_size);
875
876                // If there's a pending scroll adjustment for the scroll-top
877                // item, apply it, ensuring proportional scroll position is
878                // maintained after re-measuring.
879                if ix == 0 {
880                    if let Some(pending_scroll) = self.pending_scroll.take() {
881                        if pending_scroll.item_ix == scroll_top.item_ix {
882                            scroll_top.offset_in_item =
883                                Pixels(pending_scroll.fraction * element_size.height.0);
884                            self.logical_scroll_top = Some(scroll_top);
885                        }
886                    }
887                }
888
889                if visible_height < available_height {
890                    item_layouts.push_back(ItemLayout {
891                        index: item_index,
892                        element,
893                        size: element_size,
894                    });
895                    if item.contains_focused(window, cx) {
896                        rendered_focused_item = true;
897                    }
898                }
899            }
900
901            let size = size.unwrap();
902            rendered_height += size.height;
903            max_item_width = max_item_width.max(size.width);
904            measured_items.push_back(ListItem::Measured {
905                size,
906                focus_handle: item.focus_handle(),
907            });
908        }
909        rendered_height += padding.bottom;
910
911        // Prepare to start walking upward from the item at the scroll top.
912        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
913
914        // If the rendered items do not fill the visible region, then adjust
915        // the scroll top upward.
916        if rendered_height - scroll_top.offset_in_item < available_height {
917            while rendered_height < available_height {
918                cursor.prev();
919                if let Some(item) = cursor.item() {
920                    let item_index = cursor.start().0;
921                    let mut element = render_item(item_index, window, cx);
922                    let element_size = element.layout_as_root(available_item_space, window, cx);
923                    let focus_handle = item.focus_handle();
924                    rendered_height += element_size.height;
925                    measured_items.push_front(ListItem::Measured {
926                        size: element_size,
927                        focus_handle,
928                    });
929                    item_layouts.push_front(ItemLayout {
930                        index: item_index,
931                        element,
932                        size: element_size,
933                    });
934                    if item.contains_focused(window, cx) {
935                        rendered_focused_item = true;
936                    }
937                } else {
938                    break;
939                }
940            }
941
942            scroll_top = ListOffset {
943                item_ix: cursor.start().0,
944                offset_in_item: rendered_height - available_height,
945            };
946
947            match self.alignment {
948                ListAlignment::Top => {
949                    scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
950                    self.logical_scroll_top = Some(scroll_top);
951                }
952                ListAlignment::Bottom => {
953                    scroll_top = ListOffset {
954                        item_ix: cursor.start().0,
955                        offset_in_item: rendered_height - available_height,
956                    };
957                    self.logical_scroll_top = None;
958                }
959            };
960        }
961
962        // Measure items in the leading overdraw
963        let mut leading_overdraw = scroll_top.offset_in_item;
964        while leading_overdraw < self.overdraw {
965            cursor.prev();
966            if let Some(item) = cursor.item() {
967                let size = if let ListItem::Measured { size, .. } = item {
968                    *size
969                } else {
970                    let mut element = render_item(cursor.start().0, window, cx);
971                    element.layout_as_root(available_item_space, window, cx)
972                };
973
974                leading_overdraw += size.height;
975                measured_items.push_front(ListItem::Measured {
976                    size,
977                    focus_handle: item.focus_handle(),
978                });
979            } else {
980                break;
981            }
982        }
983
984        let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
985        let mut cursor = old_items.cursor::<Count>(());
986        let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right);
987        new_items.extend(measured_items, ());
988        cursor.seek(&Count(measured_range.end), Bias::Right);
989        new_items.append(cursor.suffix(), ());
990        self.items = new_items;
991
992        // If follow_tail mode is on but the user scrolled away
993        // (is_following is false), check whether the current scroll
994        // position has returned to the bottom.
995        if self.follow_state.has_stopped_following() {
996            let padding = self.last_padding.unwrap_or_default();
997            let total_height = self.items.summary().height + padding.top + padding.bottom;
998            let scroll_offset = self.scroll_top(&scroll_top);
999            if scroll_offset + available_height >= total_height - px(1.0) {
1000                self.follow_state.start_following();
1001            }
1002        }
1003
1004        // If none of the visible items are focused, check if an off-screen item is focused
1005        // and include it to be rendered after the visible items so keyboard interaction continues
1006        // to work for it.
1007        if !rendered_focused_item {
1008            let mut cursor = self
1009                .items
1010                .filter::<_, Count>((), |summary| summary.has_focus_handles);
1011            cursor.next();
1012            while let Some(item) = cursor.item() {
1013                if item.contains_focused(window, cx) {
1014                    let item_index = cursor.start().0;
1015                    let mut element = render_item(cursor.start().0, window, cx);
1016                    let size = element.layout_as_root(available_item_space, window, cx);
1017                    item_layouts.push_back(ItemLayout {
1018                        index: item_index,
1019                        element,
1020                        size,
1021                    });
1022                    break;
1023                }
1024                cursor.next();
1025            }
1026        }
1027
1028        LayoutItemsResponse {
1029            max_item_width,
1030            scroll_top,
1031            item_layouts,
1032        }
1033    }
1034
1035    fn prepaint_items(
1036        &mut self,
1037        bounds: Bounds<Pixels>,
1038        padding: Edges<Pixels>,
1039        autoscroll: bool,
1040        render_item: &mut RenderItemFn,
1041        window: &mut Window,
1042        cx: &mut App,
1043    ) -> Result<LayoutItemsResponse, ListOffset> {
1044        window.transact(|window| {
1045            match self.measuring_behavior {
1046                ListMeasuringBehavior::Measure(has_measured) if !has_measured => {
1047                    self.layout_all_items(bounds.size.width, render_item, window, cx);
1048                }
1049                _ => {}
1050            }
1051
1052            let mut layout_response = self.layout_items(
1053                Some(bounds.size.width),
1054                bounds.size.height,
1055                &padding,
1056                render_item,
1057                window,
1058                cx,
1059            );
1060
1061            // Avoid honoring autoscroll requests from elements other than our children.
1062            window.take_autoscroll();
1063
1064            // Only paint the visible items, if there is actually any space for them (taking padding into account)
1065            if bounds.size.height > padding.top + padding.bottom {
1066                let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
1067                item_origin.y -= layout_response.scroll_top.offset_in_item;
1068                for item in &mut layout_response.item_layouts {
1069                    window.with_content_mask(Some(ContentMask { bounds }), |window| {
1070                        item.element.prepaint_at(item_origin, window, cx);
1071                    });
1072
1073                    if let Some(autoscroll_bounds) = window.take_autoscroll()
1074                        && autoscroll
1075                    {
1076                        if autoscroll_bounds.top() < bounds.top() {
1077                            return Err(ListOffset {
1078                                item_ix: item.index,
1079                                offset_in_item: autoscroll_bounds.top() - item_origin.y,
1080                            });
1081                        } else if autoscroll_bounds.bottom() > bounds.bottom() {
1082                            let mut cursor = self.items.cursor::<Count>(());
1083                            cursor.seek(&Count(item.index), Bias::Right);
1084                            let mut height = bounds.size.height - padding.top - padding.bottom;
1085
1086                            // Account for the height of the element down until the autoscroll bottom.
1087                            height -= autoscroll_bounds.bottom() - item_origin.y;
1088
1089                            // Keep decreasing the scroll top until we fill all the available space.
1090                            while height > Pixels::ZERO {
1091                                cursor.prev();
1092                                let Some(item) = cursor.item() else { break };
1093
1094                                let size = item.size().unwrap_or_else(|| {
1095                                    let mut item = render_item(cursor.start().0, window, cx);
1096                                    let item_available_size =
1097                                        size(bounds.size.width.into(), AvailableSpace::MinContent);
1098                                    item.layout_as_root(item_available_size, window, cx)
1099                                });
1100                                height -= size.height;
1101                            }
1102
1103                            return Err(ListOffset {
1104                                item_ix: cursor.start().0,
1105                                offset_in_item: if height < Pixels::ZERO {
1106                                    -height
1107                                } else {
1108                                    Pixels::ZERO
1109                                },
1110                            });
1111                        }
1112                    }
1113
1114                    item_origin.y += item.size.height;
1115                }
1116            } else {
1117                layout_response.item_layouts.clear();
1118            }
1119
1120            Ok(layout_response)
1121        })
1122    }
1123
1124    // Scrollbar support
1125
1126    fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
1127        let Some(bounds) = self.last_layout_bounds else {
1128            return;
1129        };
1130        let height = bounds.size.height;
1131
1132        let padding = self.last_padding.unwrap_or_default();
1133        let content_height = self.items.summary().height;
1134        let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
1135        let drag_offset =
1136            // if dragging the scrollbar, we want to offset the point if the height changed
1137            content_height - self.scrollbar_drag_start_height.unwrap_or(content_height);
1138        let new_scroll_top = (point.y - drag_offset).abs().max(px(0.)).min(scroll_max);
1139
1140        self.follow_state.stop_following();
1141
1142        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
1143            self.logical_scroll_top = None;
1144        } else {
1145            let (start, _, _) =
1146                self.items
1147                    .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
1148
1149            let item_ix = start.count;
1150            let offset_in_item = new_scroll_top - start.height;
1151            self.logical_scroll_top = Some(ListOffset {
1152                item_ix,
1153                offset_in_item,
1154            });
1155        }
1156    }
1157}
1158
1159impl std::fmt::Debug for ListItem {
1160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1161        match self {
1162            Self::Unmeasured { .. } => write!(f, "Unrendered"),
1163            Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
1164        }
1165    }
1166}
1167
1168/// An offset into the list's items, in terms of the item index and the number
1169/// of pixels off the top left of the item.
1170#[derive(Debug, Clone, Copy, Default)]
1171pub struct ListOffset {
1172    /// The index of an item in the list
1173    pub item_ix: usize,
1174    /// The number of pixels to offset from the item index.
1175    pub offset_in_item: Pixels,
1176}
1177
1178impl Element for List {
1179    type RequestLayoutState = ();
1180    type PrepaintState = ListPrepaintState;
1181
1182    fn id(&self) -> Option<crate::ElementId> {
1183        None
1184    }
1185
1186    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1187        None
1188    }
1189
1190    fn request_layout(
1191        &mut self,
1192        _id: Option<&GlobalElementId>,
1193        _inspector_id: Option<&InspectorElementId>,
1194        window: &mut Window,
1195        cx: &mut App,
1196    ) -> (crate::LayoutId, Self::RequestLayoutState) {
1197        let layout_id = match self.sizing_behavior {
1198            ListSizingBehavior::Infer => {
1199                let mut style = Style::default();
1200                style.overflow.y = Overflow::Scroll;
1201                style.refine(&self.style);
1202                window.with_text_style(style.text_style().cloned(), |window| {
1203                    let state = &mut *self.state.0.borrow_mut();
1204
1205                    let available_height = if let Some(last_bounds) = state.last_layout_bounds {
1206                        last_bounds.size.height
1207                    } else {
1208                        // If we don't have the last layout bounds (first render),
1209                        // we might just use the overdraw value as the available height to layout enough items.
1210                        state.overdraw
1211                    };
1212                    let padding = style.padding.to_pixels(
1213                        state.last_layout_bounds.unwrap_or_default().size.into(),
1214                        window.rem_size(),
1215                    );
1216
1217                    let layout_response = state.layout_items(
1218                        None,
1219                        available_height,
1220                        &padding,
1221                        &mut self.render_item,
1222                        window,
1223                        cx,
1224                    );
1225                    let max_element_width = layout_response.max_item_width;
1226
1227                    let summary = state.items.summary();
1228                    let total_height = summary.height;
1229
1230                    window.request_measured_layout(
1231                        style,
1232                        move |known_dimensions, available_space, _window, _cx| {
1233                            let width =
1234                                known_dimensions
1235                                    .width
1236                                    .unwrap_or(match available_space.width {
1237                                        AvailableSpace::Definite(x) => x,
1238                                        AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1239                                            max_element_width
1240                                        }
1241                                    });
1242                            let height = match available_space.height {
1243                                AvailableSpace::Definite(height) => total_height.min(height),
1244                                AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1245                                    total_height
1246                                }
1247                            };
1248                            size(width, height)
1249                        },
1250                    )
1251                })
1252            }
1253            ListSizingBehavior::Auto => {
1254                let mut style = Style::default();
1255                style.refine(&self.style);
1256                window.with_text_style(style.text_style().cloned(), |window| {
1257                    window.request_layout(style, None, cx)
1258                })
1259            }
1260        };
1261        (layout_id, ())
1262    }
1263
1264    fn prepaint(
1265        &mut self,
1266        _id: Option<&GlobalElementId>,
1267        _inspector_id: Option<&InspectorElementId>,
1268        bounds: Bounds<Pixels>,
1269        _: &mut Self::RequestLayoutState,
1270        window: &mut Window,
1271        cx: &mut App,
1272    ) -> ListPrepaintState {
1273        let state = &mut *self.state.0.borrow_mut();
1274        state.reset = false;
1275
1276        let mut style = Style::default();
1277        style.refine(&self.style);
1278
1279        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1280
1281        // If the width of the list has changed, invalidate all cached item heights
1282        if state
1283            .last_layout_bounds
1284            .is_none_or(|last_bounds| last_bounds.size.width != bounds.size.width)
1285        {
1286            let new_items = SumTree::from_iter(
1287                state.items.iter().map(|item| ListItem::Unmeasured {
1288                    size_hint: None,
1289                    focus_handle: item.focus_handle(),
1290                }),
1291                (),
1292            );
1293
1294            state.items = new_items;
1295            state.measuring_behavior.reset();
1296        }
1297
1298        let padding = style
1299            .padding
1300            .to_pixels(bounds.size.into(), window.rem_size());
1301        let layout =
1302            match state.prepaint_items(bounds, padding, true, &mut self.render_item, window, cx) {
1303                Ok(layout) => layout,
1304                Err(autoscroll_request) => {
1305                    state.logical_scroll_top = Some(autoscroll_request);
1306                    state
1307                        .prepaint_items(bounds, padding, false, &mut self.render_item, window, cx)
1308                        .unwrap()
1309                }
1310            };
1311
1312        state.last_layout_bounds = Some(bounds);
1313        state.last_padding = Some(padding);
1314        ListPrepaintState { hitbox, layout }
1315    }
1316
1317    fn paint(
1318        &mut self,
1319        _id: Option<&GlobalElementId>,
1320        _inspector_id: Option<&InspectorElementId>,
1321        bounds: Bounds<crate::Pixels>,
1322        _: &mut Self::RequestLayoutState,
1323        prepaint: &mut Self::PrepaintState,
1324        window: &mut Window,
1325        cx: &mut App,
1326    ) {
1327        let current_view = window.current_view();
1328        window.with_content_mask(Some(ContentMask { bounds }), |window| {
1329            for item in &mut prepaint.layout.item_layouts {
1330                item.element.paint(window, cx);
1331            }
1332        });
1333
1334        let list_state = self.state.clone();
1335        let height = bounds.size.height;
1336        let scroll_top = prepaint.layout.scroll_top;
1337        let hitbox_id = prepaint.hitbox.id;
1338        let mut accumulated_scroll_delta = ScrollDelta::default();
1339        window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
1340            if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
1341                accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
1342                let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1343                list_state.0.borrow_mut().scroll(
1344                    &scroll_top,
1345                    height,
1346                    pixel_delta,
1347                    current_view,
1348                    window,
1349                    cx,
1350                )
1351            }
1352        });
1353    }
1354}
1355
1356impl IntoElement for List {
1357    type Element = Self;
1358
1359    fn into_element(self) -> Self::Element {
1360        self
1361    }
1362}
1363
1364impl Styled for List {
1365    fn style(&mut self) -> &mut StyleRefinement {
1366        &mut self.style
1367    }
1368}
1369
1370impl sum_tree::Item for ListItem {
1371    type Summary = ListItemSummary;
1372
1373    fn summary(&self, _: ()) -> Self::Summary {
1374        match self {
1375            ListItem::Unmeasured {
1376                size_hint,
1377                focus_handle,
1378            } => ListItemSummary {
1379                count: 1,
1380                rendered_count: 0,
1381                unrendered_count: 1,
1382                height: if let Some(size) = size_hint {
1383                    size.height
1384                } else {
1385                    px(0.)
1386                },
1387                has_focus_handles: focus_handle.is_some(),
1388            },
1389            ListItem::Measured {
1390                size, focus_handle, ..
1391            } => ListItemSummary {
1392                count: 1,
1393                rendered_count: 1,
1394                unrendered_count: 0,
1395                height: size.height,
1396                has_focus_handles: focus_handle.is_some(),
1397            },
1398        }
1399    }
1400}
1401
1402impl sum_tree::ContextLessSummary for ListItemSummary {
1403    fn zero() -> Self {
1404        Default::default()
1405    }
1406
1407    fn add_summary(&mut self, summary: &Self) {
1408        self.count += summary.count;
1409        self.rendered_count += summary.rendered_count;
1410        self.unrendered_count += summary.unrendered_count;
1411        self.height += summary.height;
1412        self.has_focus_handles |= summary.has_focus_handles;
1413    }
1414}
1415
1416impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1417    fn zero(_cx: ()) -> Self {
1418        Default::default()
1419    }
1420
1421    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1422        self.0 += summary.count;
1423    }
1424}
1425
1426impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1427    fn zero(_cx: ()) -> Self {
1428        Default::default()
1429    }
1430
1431    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1432        self.0 += summary.height;
1433    }
1434}
1435
1436impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1437    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1438        self.0.partial_cmp(&other.count).unwrap()
1439    }
1440}
1441
1442impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1443    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1444        self.0.partial_cmp(&other.height).unwrap()
1445    }
1446}
1447
1448#[cfg(test)]
1449mod test {
1450
1451    use gpui::{ScrollDelta, ScrollWheelEvent};
1452    use std::cell::Cell;
1453    use std::rc::Rc;
1454
1455    use crate::{
1456        self as gpui, AppContext, Context, Element, FollowMode, IntoElement, ListState, Render,
1457        Styled, TestAppContext, Window, div, list, point, px, size,
1458    };
1459
1460    #[gpui::test]
1461    fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
1462        let cx = cx.add_empty_window();
1463
1464        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1465
1466        // Ensure that the list is scrolled to the top
1467        state.scroll_to(gpui::ListOffset {
1468            item_ix: 0,
1469            offset_in_item: px(0.0),
1470        });
1471
1472        struct TestView(ListState);
1473        impl Render for TestView {
1474            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1475                list(self.0.clone(), |_, _, _| {
1476                    div().h(px(10.)).w_full().into_any()
1477                })
1478                .w_full()
1479                .h_full()
1480            }
1481        }
1482
1483        // Paint
1484        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1485            cx.new(|_| TestView(state.clone())).into_any_element()
1486        });
1487
1488        // Reset
1489        state.reset(5);
1490
1491        // And then receive a scroll event _before_ the next paint
1492        cx.simulate_event(ScrollWheelEvent {
1493            position: point(px(1.), px(1.)),
1494            delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
1495            ..Default::default()
1496        });
1497
1498        // Scroll position should stay at the top of the list
1499        assert_eq!(state.logical_scroll_top().item_ix, 0);
1500        assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
1501    }
1502
1503    #[gpui::test]
1504    fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
1505        let cx = cx.add_empty_window();
1506
1507        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1508
1509        struct TestView(ListState);
1510        impl Render for TestView {
1511            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1512                list(self.0.clone(), |_, _, _| {
1513                    div().h(px(20.)).w_full().into_any()
1514                })
1515                .w_full()
1516                .h_full()
1517            }
1518        }
1519
1520        // Paint
1521        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1522            cx.new(|_| TestView(state.clone())).into_any_element()
1523        });
1524
1525        // Test positive distance: start at item 1, move down 30px
1526        state.scroll_by(px(30.));
1527
1528        // Should move to item 2
1529        let offset = state.logical_scroll_top();
1530        assert_eq!(offset.item_ix, 1);
1531        assert_eq!(offset.offset_in_item, px(10.));
1532
1533        // Test negative distance: start at item 2, move up 30px
1534        state.scroll_by(px(-30.));
1535
1536        // Should move back to item 1
1537        let offset = state.logical_scroll_top();
1538        assert_eq!(offset.item_ix, 0);
1539        assert_eq!(offset.offset_in_item, px(0.));
1540
1541        // Test zero distance
1542        state.scroll_by(px(0.));
1543        let offset = state.logical_scroll_top();
1544        assert_eq!(offset.item_ix, 0);
1545        assert_eq!(offset.offset_in_item, px(0.));
1546    }
1547
1548    #[gpui::test]
1549    fn test_measure_all_after_width_change(cx: &mut TestAppContext) {
1550        let cx = cx.add_empty_window();
1551
1552        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
1553
1554        struct TestView(ListState);
1555        impl Render for TestView {
1556            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1557                list(self.0.clone(), |_, _, _| {
1558                    div().h(px(50.)).w_full().into_any()
1559                })
1560                .w_full()
1561                .h_full()
1562            }
1563        }
1564
1565        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1566
1567        // First draw at width 100: all 10 items measured (total 500px).
1568        // Viewport is 200px, so max scroll offset should be 300px.
1569        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1570            view.clone().into_any_element()
1571        });
1572        assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
1573
1574        // Second draw at a different width: items get invalidated.
1575        // Without the fix, max_offset would drop because unmeasured items
1576        // contribute 0 height.
1577        cx.draw(point(px(0.), px(0.)), size(px(200.), px(200.)), |_, _| {
1578            view.into_any_element()
1579        });
1580        assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
1581    }
1582
1583    #[gpui::test]
1584    fn test_remeasure(cx: &mut TestAppContext) {
1585        let cx = cx.add_empty_window();
1586
1587        // Create a list with 10 items, each 100px tall. We'll keep a reference
1588        // to the item height so we can later change the height and assert how
1589        // `ListState` handles it.
1590        let item_height = Rc::new(Cell::new(100usize));
1591        let state = ListState::new(10, crate::ListAlignment::Top, px(10.));
1592
1593        struct TestView {
1594            state: ListState,
1595            item_height: Rc<Cell<usize>>,
1596        }
1597
1598        impl Render for TestView {
1599            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1600                let height = self.item_height.get();
1601                list(self.state.clone(), move |_, _, _| {
1602                    div().h(px(height as f32)).w_full().into_any()
1603                })
1604                .w_full()
1605                .h_full()
1606            }
1607        }
1608
1609        let state_clone = state.clone();
1610        let item_height_clone = item_height.clone();
1611        let view = cx.update(|_, cx| {
1612            cx.new(|_| TestView {
1613                state: state_clone,
1614                item_height: item_height_clone,
1615            })
1616        });
1617
1618        // Simulate scrolling 40px inside the element with index 2. Since the
1619        // original item height is 100px, this equates to 40% inside the item.
1620        state.scroll_to(gpui::ListOffset {
1621            item_ix: 2,
1622            offset_in_item: px(40.),
1623        });
1624
1625        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1626            view.clone().into_any_element()
1627        });
1628
1629        let offset = state.logical_scroll_top();
1630        assert_eq!(offset.item_ix, 2);
1631        assert_eq!(offset.offset_in_item, px(40.));
1632
1633        // Update the `item_height` to be 50px instead of 100px so we can assert
1634        // that the scroll position is proportionally preserved, that is,
1635        // instead of 40px from the top of item 2, it should be 20px, since the
1636        // item's height has been halved.
1637        item_height.set(50);
1638        state.remeasure();
1639
1640        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1641            view.into_any_element()
1642        });
1643
1644        let offset = state.logical_scroll_top();
1645        assert_eq!(offset.item_ix, 2);
1646        assert_eq!(offset.offset_in_item, px(20.));
1647    }
1648
1649    #[gpui::test]
1650    fn test_follow_tail_stays_at_bottom_as_items_grow(cx: &mut TestAppContext) {
1651        let cx = cx.add_empty_window();
1652
1653        // 10 items, each 50px tall → 500px total content, 200px viewport.
1654        // With follow-tail on, the list should always show the bottom.
1655        let item_height = Rc::new(Cell::new(50usize));
1656        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
1657
1658        struct TestView {
1659            state: ListState,
1660            item_height: Rc<Cell<usize>>,
1661        }
1662        impl Render for TestView {
1663            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1664                let height = self.item_height.get();
1665                list(self.state.clone(), move |_, _, _| {
1666                    div().h(px(height as f32)).w_full().into_any()
1667                })
1668                .w_full()
1669                .h_full()
1670            }
1671        }
1672
1673        let state_clone = state.clone();
1674        let item_height_clone = item_height.clone();
1675        let view = cx.update(|_, cx| {
1676            cx.new(|_| TestView {
1677                state: state_clone,
1678                item_height: item_height_clone,
1679            })
1680        });
1681
1682        state.set_follow_mode(FollowMode::Tail);
1683
1684        // First paint — items are 50px, total 500px, viewport 200px.
1685        // Follow-tail should anchor to the end.
1686        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1687            view.clone().into_any_element()
1688        });
1689
1690        // The scroll should be at the bottom: the last visible items fill the
1691        // 200px viewport from the end of 500px of content (offset 300px).
1692        let offset = state.logical_scroll_top();
1693        assert_eq!(offset.item_ix, 6);
1694        assert_eq!(offset.offset_in_item, px(0.));
1695        assert!(state.is_following_tail());
1696
1697        // Simulate items growing (e.g. streaming content makes each item taller).
1698        // 10 items × 80px = 800px total.
1699        item_height.set(80);
1700        state.remeasure();
1701
1702        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1703            view.into_any_element()
1704        });
1705
1706        // After growth, follow-tail should have re-anchored to the new end.
1707        // 800px total − 200px viewport = 600px offset → item 7 at offset 40px,
1708        // but follow-tail anchors to item_count (10), and layout walks back to
1709        // fill 200px, landing at item 7 (7 × 80 = 560, 800 − 560 = 240 > 200,
1710        // so item 8: 8 × 80 = 640, 800 − 640 = 160 < 200 → keeps walking →
1711        // item 7: offset = 800 − 200 = 600, item_ix = 600/80 = 7, remainder 40).
1712        let offset = state.logical_scroll_top();
1713        assert_eq!(offset.item_ix, 7);
1714        assert_eq!(offset.offset_in_item, px(40.));
1715        assert!(state.is_following_tail());
1716    }
1717
1718    #[gpui::test]
1719    fn test_follow_tail_disengages_on_user_scroll(cx: &mut TestAppContext) {
1720        let cx = cx.add_empty_window();
1721
1722        // 10 items × 50px = 500px total, 200px viewport.
1723        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
1724
1725        struct TestView(ListState);
1726        impl Render for TestView {
1727            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1728                list(self.0.clone(), |_, _, _| {
1729                    div().h(px(50.)).w_full().into_any()
1730                })
1731                .w_full()
1732                .h_full()
1733            }
1734        }
1735
1736        state.set_follow_mode(FollowMode::Tail);
1737
1738        // Paint with follow-tail — scroll anchored to the bottom.
1739        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, cx| {
1740            cx.new(|_| TestView(state.clone())).into_any_element()
1741        });
1742        assert!(state.is_following_tail());
1743
1744        // Simulate the user scrolling up.
1745        // This should disengage follow-tail.
1746        cx.simulate_event(ScrollWheelEvent {
1747            position: point(px(50.), px(100.)),
1748            delta: ScrollDelta::Pixels(point(px(0.), px(100.))),
1749            ..Default::default()
1750        });
1751
1752        assert!(
1753            !state.is_following_tail(),
1754            "follow-tail should disengage when the user scrolls toward the start"
1755        );
1756    }
1757
1758    #[gpui::test]
1759    fn test_follow_tail_disengages_on_scrollbar_reposition(cx: &mut TestAppContext) {
1760        let cx = cx.add_empty_window();
1761
1762        // 10 items × 50px = 500px total, 200px viewport.
1763        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
1764
1765        struct TestView(ListState);
1766        impl Render for TestView {
1767            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1768                list(self.0.clone(), |_, _, _| {
1769                    div().h(px(50.)).w_full().into_any()
1770                })
1771                .w_full()
1772                .h_full()
1773            }
1774        }
1775
1776        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1777
1778        state.set_follow_mode(FollowMode::Tail);
1779
1780        // Paint with follow-tail — scroll anchored to the bottom.
1781        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1782            view.clone().into_any_element()
1783        });
1784        assert!(state.is_following_tail());
1785
1786        // Simulate the scrollbar moving the viewport to the middle.
1787        // `set_offset_from_scrollbar` accepts a positive distance from the start.
1788        state.set_offset_from_scrollbar(point(px(0.), px(150.)));
1789
1790        let offset = state.logical_scroll_top();
1791        assert_eq!(offset.item_ix, 3);
1792        assert_eq!(offset.offset_in_item, px(0.));
1793        assert!(
1794            !state.is_following_tail(),
1795            "follow-tail should disengage when the scrollbar manually repositions the list"
1796        );
1797
1798        // A subsequent draw should preserve the user's manual position instead
1799        // of snapping back to the end.
1800        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1801            view.into_any_element()
1802        });
1803
1804        let offset = state.logical_scroll_top();
1805        assert_eq!(offset.item_ix, 3);
1806        assert_eq!(offset.offset_in_item, px(0.));
1807    }
1808
1809    #[gpui::test]
1810    fn test_set_follow_tail_snaps_to_bottom(cx: &mut TestAppContext) {
1811        let cx = cx.add_empty_window();
1812
1813        // 10 items × 50px = 500px total, 200px viewport.
1814        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
1815
1816        struct TestView(ListState);
1817        impl Render for TestView {
1818            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1819                list(self.0.clone(), |_, _, _| {
1820                    div().h(px(50.)).w_full().into_any()
1821                })
1822                .w_full()
1823                .h_full()
1824            }
1825        }
1826
1827        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1828
1829        // Scroll to the middle of the list (item 3).
1830        state.scroll_to(gpui::ListOffset {
1831            item_ix: 3,
1832            offset_in_item: px(0.),
1833        });
1834
1835        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1836            view.clone().into_any_element()
1837        });
1838
1839        let offset = state.logical_scroll_top();
1840        assert_eq!(offset.item_ix, 3);
1841        assert_eq!(offset.offset_in_item, px(0.));
1842        assert!(!state.is_following_tail());
1843
1844        // Enable follow-tail — this should immediately snap the scroll anchor
1845        // to the end, like the user just sent a prompt.
1846        state.set_follow_mode(FollowMode::Tail);
1847
1848        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1849            view.into_any_element()
1850        });
1851
1852        // After paint, scroll should be at the bottom.
1853        // 500px total − 200px viewport = 300px offset → item 6, offset 0.
1854        let offset = state.logical_scroll_top();
1855        assert_eq!(offset.item_ix, 6);
1856        assert_eq!(offset.offset_in_item, px(0.));
1857        assert!(state.is_following_tail());
1858    }
1859
1860    #[gpui::test]
1861    fn test_bottom_aligned_scrollbar_offset_at_end(cx: &mut TestAppContext) {
1862        let cx = cx.add_empty_window();
1863
1864        const ITEMS: usize = 10;
1865        const ITEM_SIZE: f32 = 50.0;
1866
1867        let state = ListState::new(
1868            ITEMS,
1869            crate::ListAlignment::Bottom,
1870            px(ITEMS as f32 * ITEM_SIZE),
1871        );
1872
1873        struct TestView(ListState);
1874        impl Render for TestView {
1875            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1876                list(self.0.clone(), |_, _, _| {
1877                    div().h(px(ITEM_SIZE)).w_full().into_any()
1878                })
1879                .w_full()
1880                .h_full()
1881            }
1882        }
1883
1884        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1885            cx.new(|_| TestView(state.clone())).into_any_element()
1886        });
1887
1888        // Bottom-aligned lists start pinned to the end: logical_scroll_top returns
1889        // item_ix == item_count, meaning no explicit scroll position has been set.
1890        assert_eq!(state.logical_scroll_top().item_ix, ITEMS);
1891
1892        let max_offset = state.max_offset_for_scrollbar();
1893        let scroll_offset = state.scroll_px_offset_for_scrollbar();
1894
1895        assert_eq!(
1896            -scroll_offset.y, max_offset.y,
1897            "scrollbar offset ({}) should equal max offset ({}) when list is pinned to bottom",
1898            -scroll_offset.y, max_offset.y,
1899        );
1900    }
1901
1902    /// When the user scrolls away from the bottom during follow_tail,
1903    /// follow_tail suspends. If they scroll back to the bottom, the
1904    /// next paint should re-engage follow_tail using fresh measurements.
1905    #[gpui::test]
1906    fn test_follow_tail_reengages_when_scrolled_back_to_bottom(cx: &mut TestAppContext) {
1907        let cx = cx.add_empty_window();
1908
1909        // 10 items × 50px = 500px total, 200px viewport.
1910        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
1911
1912        struct TestView(ListState);
1913        impl Render for TestView {
1914            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1915                list(self.0.clone(), |_, _, _| {
1916                    div().h(px(50.)).w_full().into_any()
1917                })
1918                .w_full()
1919                .h_full()
1920            }
1921        }
1922
1923        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1924
1925        state.set_follow_mode(FollowMode::Tail);
1926
1927        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1928            view.clone().into_any_element()
1929        });
1930        assert!(state.is_following_tail());
1931
1932        // Scroll up — follow_tail should suspend (not fully disengage).
1933        cx.simulate_event(ScrollWheelEvent {
1934            position: point(px(50.), px(100.)),
1935            delta: ScrollDelta::Pixels(point(px(0.), px(50.))),
1936            ..Default::default()
1937        });
1938        assert!(!state.is_following_tail());
1939
1940        // Scroll back down to the bottom.
1941        cx.simulate_event(ScrollWheelEvent {
1942            position: point(px(50.), px(100.)),
1943            delta: ScrollDelta::Pixels(point(px(0.), px(-10000.))),
1944            ..Default::default()
1945        });
1946
1947        // After a paint, follow_tail should re-engage because the
1948        // layout confirmed we're at the true bottom.
1949        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1950            view.clone().into_any_element()
1951        });
1952        assert!(
1953            state.is_following_tail(),
1954            "follow_tail should re-engage after scrolling back to the bottom"
1955        );
1956    }
1957
1958    /// When an item is spliced to unmeasured (0px) while follow_tail
1959    /// is suspended, the re-engagement check should still work correctly
1960    #[gpui::test]
1961    fn test_follow_tail_reengagement_not_fooled_by_unmeasured_items(cx: &mut TestAppContext) {
1962        let cx = cx.add_empty_window();
1963
1964        // 20 items × 50px = 1000px total, 200px viewport, 1000px
1965        // overdraw so all items get measured during the follow_tail
1966        // paint (matching realistic production settings).
1967        let state = ListState::new(20, crate::ListAlignment::Top, px(1000.));
1968
1969        struct TestView(ListState);
1970        impl Render for TestView {
1971            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1972                list(self.0.clone(), |_, _, _| {
1973                    div().h(px(50.)).w_full().into_any()
1974                })
1975                .w_full()
1976                .h_full()
1977            }
1978        }
1979
1980        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1981
1982        state.set_follow_mode(FollowMode::Tail);
1983
1984        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1985            view.clone().into_any_element()
1986        });
1987        assert!(state.is_following_tail());
1988
1989        // Scroll up a meaningful amount — suspends follow_tail.
1990        // 20 items × 50px = 1000px. viewport 200px. scroll_max = 800px.
1991        // Scrolling up 200px puts us at 600px, clearly not at bottom.
1992        cx.simulate_event(ScrollWheelEvent {
1993            position: point(px(50.), px(100.)),
1994            delta: ScrollDelta::Pixels(point(px(0.), px(200.))),
1995            ..Default::default()
1996        });
1997        assert!(!state.is_following_tail());
1998
1999        // Invalidate the last item (simulates EntryUpdated calling
2000        // remeasure_items). This makes items.summary().height
2001        // temporarily wrong (0px for the invalidated item).
2002        state.remeasure_items(19..20);
2003
2004        // Paint — layout re-measures the invalidated item with its true
2005        // height. The re-engagement check uses these fresh measurements.
2006        // Since we scrolled 200px up from the 800px max, we're at
2007        // ~600px — NOT at the bottom, so follow_tail should NOT
2008        // re-engage.
2009        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2010            view.clone().into_any_element()
2011        });
2012        assert!(
2013            !state.is_following_tail(),
2014            "follow_tail should not falsely re-engage due to an unmeasured item \
2015             reducing items.summary().height"
2016        );
2017    }
2018
2019    #[gpui::test]
2020    fn test_follow_tail_reengages_after_scrollbar_disengagement(cx: &mut TestAppContext) {
2021        let cx = cx.add_empty_window();
2022
2023        // 10 items × 50px = 500px total, 200px viewport, scroll_max = 300px.
2024        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2025
2026        struct TestView(ListState);
2027        impl Render for TestView {
2028            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2029                list(self.0.clone(), |_, _, _| {
2030                    div().h(px(50.)).w_full().into_any()
2031                })
2032                .w_full()
2033                .h_full()
2034            }
2035        }
2036
2037        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2038
2039        state.set_follow_mode(FollowMode::Tail);
2040        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2041            view.clone().into_any_element()
2042        });
2043        assert!(state.is_following_tail());
2044
2045        // Drag the scrollbar up to the middle — follow_tail should suspend.
2046        state.set_offset_from_scrollbar(point(px(0.), px(150.)));
2047        assert!(!state.is_following_tail());
2048
2049        // Drag the scrollbar back to the bottom — follow_tail should re-engage
2050        // on the next paint.
2051        state.set_offset_from_scrollbar(point(px(0.), px(300.)));
2052        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2053            view.into_any_element()
2054        });
2055        assert!(
2056            state.is_following_tail(),
2057            "follow_tail should re-engage after scrolling back to the bottom via the scrollbar"
2058        );
2059    }
2060}