Skip to main content

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<PendingScroll>,
75    follow_state: FollowState,
76}
77
78/// Deferred scroll adjustment applied after the scroll-top item has been remeasured.
79///
80/// An absolute pending scroll preserves the same pixel offset into the item, which keeps
81/// visible text stable while content is appended to or removed from that item. A
82/// proportional pending scroll preserves the same fractional position within the item,
83/// which is useful when the whole list is being resized and each item scales similarly.
84#[derive(Clone)]
85enum PendingScroll {
86    /// Preserve the same pixel offset into the item after it is remeasured.
87    Absolute { item_ix: usize, offset: Pixels },
88    /// Preserve the same fractional offset into the item after it is remeasured.
89    Proportional(PendingScrollFraction),
90}
91
92/// Keeps track of a fractional scroll position within an item for restoration
93/// after remeasurement.
94#[derive(Clone)]
95struct PendingScrollFraction {
96    /// The index of the item to scroll within.
97    item_ix: usize,
98    /// Fractional offset (0.0 to 1.0) within the item's height.
99    fraction: f32,
100}
101
102/// Determines how remeasurement preserves the scroll position when the scroll-top item
103/// changes height.
104enum ScrollAnchor {
105    /// Preserve the same pixel offset into the scroll-top item.
106    Absolute,
107    /// Preserve the same fractional position within the scroll-top item.
108    Proportional,
109}
110
111/// Controls whether the list automatically follows new content at the end.
112#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
113pub enum FollowMode {
114    /// Normal scrolling — no automatic following.
115    #[default]
116    Normal,
117    /// The list should auto-scroll along with the tail, when scrolled to bottom.
118    Tail,
119}
120
121#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
122enum FollowState {
123    #[default]
124    Normal,
125    Tail {
126        is_following: bool,
127    },
128}
129
130impl FollowState {
131    fn is_following(&self) -> bool {
132        matches!(self, FollowState::Tail { is_following: true })
133    }
134
135    fn has_stopped_following(&self) -> bool {
136        matches!(
137            self,
138            FollowState::Tail {
139                is_following: false
140            }
141        )
142    }
143
144    fn start_following(&mut self) {
145        if let FollowState::Tail {
146            is_following: false,
147        } = self
148        {
149            *self = FollowState::Tail { is_following: true };
150        }
151    }
152
153    fn stop_following(&mut self) {
154        if let FollowState::Tail { is_following: true } = self {
155            *self = FollowState::Tail {
156                is_following: false,
157            };
158        }
159    }
160}
161
162/// Whether the list is scrolling from top to bottom or bottom to top.
163#[derive(Clone, Copy, Debug, Eq, PartialEq)]
164pub enum ListAlignment {
165    /// The list is scrolling from top to bottom, like most lists.
166    Top,
167    /// The list is scrolling from bottom to top, like a chat log.
168    Bottom,
169}
170
171/// A scroll event that has been converted to be in terms of the list's items.
172pub struct ListScrollEvent {
173    /// The range of items currently visible in the list, after applying the scroll event.
174    pub visible_range: Range<usize>,
175
176    /// The number of items that are currently visible in the list, after applying the scroll event.
177    pub count: usize,
178
179    /// Whether the list has been scrolled.
180    pub is_scrolled: bool,
181
182    /// Whether the list is currently in follow-tail mode (auto-scrolling to end).
183    pub is_following_tail: bool,
184}
185
186/// The sizing behavior to apply during layout.
187#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
188pub enum ListSizingBehavior {
189    /// The list should calculate its size based on the size of its items.
190    Infer,
191    /// The list should not calculate a fixed size.
192    #[default]
193    Auto,
194}
195
196/// The measuring behavior to apply during layout.
197#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
198pub enum ListMeasuringBehavior {
199    /// Measure all items in the list.
200    /// Note: This can be expensive for the first frame in a large list.
201    Measure(bool),
202    /// Only measure visible items
203    #[default]
204    Visible,
205}
206
207impl ListMeasuringBehavior {
208    fn reset(&mut self) {
209        match self {
210            ListMeasuringBehavior::Measure(has_measured) => *has_measured = false,
211            ListMeasuringBehavior::Visible => {}
212        }
213    }
214}
215
216/// The horizontal sizing behavior to apply during layout.
217#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
218pub enum ListHorizontalSizingBehavior {
219    /// List items' width can never exceed the width of the list.
220    #[default]
221    FitList,
222    /// List items' width may go over the width of the list, if any item is wider.
223    Unconstrained,
224}
225
226struct LayoutItemsResponse {
227    max_item_width: Pixels,
228    scroll_top: ListOffset,
229    item_layouts: VecDeque<ItemLayout>,
230}
231
232struct ItemLayout {
233    index: usize,
234    element: AnyElement,
235    size: Size<Pixels>,
236}
237
238/// Frame state used by the [List] element after layout.
239pub struct ListPrepaintState {
240    hitbox: Hitbox,
241    layout: LayoutItemsResponse,
242}
243
244#[derive(Clone)]
245enum ListItem {
246    Unmeasured {
247        size_hint: Option<Size<Pixels>>,
248        focus_handle: Option<FocusHandle>,
249    },
250    Measured {
251        size: Size<Pixels>,
252        focus_handle: Option<FocusHandle>,
253    },
254}
255
256impl ListItem {
257    fn size(&self) -> Option<Size<Pixels>> {
258        if let ListItem::Measured { size, .. } = self {
259            Some(*size)
260        } else {
261            None
262        }
263    }
264
265    fn size_hint(&self) -> Option<Size<Pixels>> {
266        match self {
267            ListItem::Measured { size, .. } => Some(*size),
268            ListItem::Unmeasured { size_hint, .. } => *size_hint,
269        }
270    }
271
272    fn focus_handle(&self) -> Option<FocusHandle> {
273        match self {
274            ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
275                focus_handle.clone()
276            }
277        }
278    }
279
280    fn contains_focused(&self, window: &Window, cx: &App) -> bool {
281        match self {
282            ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
283                focus_handle
284                    .as_ref()
285                    .is_some_and(|handle| handle.contains_focused(window, cx))
286            }
287        }
288    }
289}
290
291#[derive(Clone, Debug, Default, PartialEq)]
292struct ListItemSummary {
293    count: usize,
294    rendered_count: usize,
295    unrendered_count: usize,
296    height: Pixels,
297    has_focus_handles: bool,
298    has_unknown_height: bool,
299}
300
301#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
302struct Count(usize);
303
304#[derive(Clone, Debug, Default)]
305struct Height(Pixels);
306
307impl ListState {
308    /// Construct a new list state, for storage on a view.
309    ///
310    /// The overdraw parameter controls how much extra space is rendered
311    /// above and below the visible area. Elements within this area will
312    /// be measured even though they are not visible. This can help ensure
313    /// that the list doesn't flicker or pop in when scrolling.
314    pub fn new(item_count: usize, alignment: ListAlignment, overdraw: Pixels) -> Self {
315        let this = Self(Rc::new(RefCell::new(StateInner {
316            last_layout_bounds: None,
317            last_padding: None,
318            items: SumTree::default(),
319            logical_scroll_top: None,
320            alignment,
321            overdraw,
322            scroll_handler: None,
323            reset: false,
324            scrollbar_drag_start_height: None,
325            measuring_behavior: ListMeasuringBehavior::default(),
326            pending_scroll: None,
327            follow_state: FollowState::default(),
328        })));
329        this.splice(0..0, item_count);
330        this
331    }
332
333    /// Set the list to measure all items in the list in the first layout phase.
334    ///
335    /// This is useful for ensuring that the scrollbar size is correct instead of based on only rendered elements.
336    pub fn measure_all(self) -> Self {
337        self.0.borrow_mut().measuring_behavior = ListMeasuringBehavior::Measure(false);
338        self
339    }
340
341    /// Pre-populate every unmeasured item with a uniform height hint so the scrollbar thumb
342    /// is correctly sized from the first frame, without measuring all items up front.
343    ///
344    /// As items are actually rendered their real heights replace the hint, so the scrollbar
345    /// converges to the exact size over time. This is a cheaper alternative to [`Self::measure_all`]
346    /// for lists where items have roughly uniform heights (e.g. table rows).
347    pub fn with_uniform_item_height(self, height: Pixels) -> Self {
348        self.apply_uniform_item_height(height);
349        self
350    }
351
352    /// Reset this instantiation of the list state.
353    ///
354    /// Note that this will cause scroll events to be dropped until the next paint.
355    pub fn reset(&self, element_count: usize) {
356        let old_count = {
357            let state = &mut *self.0.borrow_mut();
358            state.reset = true;
359            state.measuring_behavior.reset();
360            state.logical_scroll_top = None;
361            state.pending_scroll = None;
362            state.scrollbar_drag_start_height = None;
363            state.items.summary().count
364        };
365
366        self.splice(0..old_count, element_count);
367    }
368
369    /// Reset the list to `element_count` items, pre-populating every item with a
370    /// uniform height hint so the scrollbar thumb is correctly sized from the first
371    /// frame even for off-screen items.
372    pub fn reset_with_uniform_height(&self, element_count: usize, height: Pixels) {
373        self.reset(element_count);
374        self.apply_uniform_item_height(height);
375    }
376
377    fn apply_uniform_item_height(&self, height: Pixels) {
378        let size_hint = Size {
379            width: px(0.),
380            height,
381        };
382        let mut state = self.0.borrow_mut();
383        let new_items = state
384            .items
385            .iter()
386            .map(|item| ListItem::Unmeasured {
387                size_hint: Some(item.size_hint().unwrap_or(size_hint)),
388                focus_handle: item.focus_handle(),
389            })
390            .collect::<Vec<_>>();
391        let mut tree = SumTree::default();
392        tree.extend(new_items, ());
393        state.items = tree;
394    }
395
396    /// Remeasure all items while preserving proportional scroll position.
397    ///
398    /// Use this when item heights may have changed (e.g., font size changes)
399    /// but the number and identity of items remains the same.
400    pub fn remeasure(&self) {
401        let count = self.item_count();
402        self.remeasure_items_with_scroll_anchor(0..count, ScrollAnchor::Proportional);
403    }
404
405    /// Mark items in `range` as needing remeasurement while preserving
406    /// the current scroll position. Unlike [`Self::splice`], this does
407    /// not change the number of items or blow away `logical_scroll_top`.
408    ///
409    /// Use this when an item's content has changed and its rendered
410    /// height may be different (e.g., streaming text, tool results
411    /// loading), but the item itself still exists at the same index.
412    pub fn remeasure_items(&self, range: Range<usize>) {
413        self.remeasure_items_with_scroll_anchor(range, ScrollAnchor::Absolute);
414    }
415
416    fn remeasure_items_with_scroll_anchor(&self, range: Range<usize>, scroll_anchor: ScrollAnchor) {
417        let state = &mut *self.0.borrow_mut();
418
419        if let Some(scroll_top) = state.logical_scroll_top {
420            if range.contains(&scroll_top.item_ix) {
421                state.pending_scroll = match scroll_anchor {
422                    ScrollAnchor::Absolute => Some(PendingScroll::Absolute {
423                        item_ix: scroll_top.item_ix,
424                        offset: scroll_top.offset_in_item,
425                    }),
426                    ScrollAnchor::Proportional => {
427                        // If the scroll-top item falls within the remeasured range,
428                        // store a fractional offset so the layout can restore the
429                        // proportional scroll position after the item is re-rendered
430                        // at its new height.
431                        let mut cursor = state.items.cursor::<Count>(());
432                        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
433
434                        cursor
435                            .item()
436                            .and_then(|item| {
437                                item.size().map(|size| {
438                                    let fraction = if size.height.0 > 0.0 {
439                                        (scroll_top.offset_in_item.0 / size.height.0)
440                                            .clamp(0.0, 1.0)
441                                    } else {
442                                        0.0
443                                    };
444
445                                    PendingScroll::Proportional(PendingScrollFraction {
446                                        item_ix: scroll_top.item_ix,
447                                        fraction,
448                                    })
449                                })
450                            })
451                            .or_else(|| state.pending_scroll.clone())
452                    }
453                };
454            }
455        }
456
457        // Rebuild the tree, replacing items in the range with
458        // Unmeasured copies that keep their focus handles.
459        let new_items = {
460            let mut cursor = state.items.cursor::<Count>(());
461            let mut new_items = cursor.slice(&Count(range.start), Bias::Right);
462            let invalidated = cursor.slice(&Count(range.end), Bias::Right);
463            new_items.extend(
464                invalidated.iter().map(|item| ListItem::Unmeasured {
465                    size_hint: item.size_hint(),
466                    focus_handle: item.focus_handle(),
467                }),
468                (),
469            );
470            new_items.append(cursor.suffix(), ());
471            new_items
472        };
473        state.items = new_items;
474        state.measuring_behavior.reset();
475    }
476
477    /// The number of items in this list.
478    pub fn item_count(&self) -> usize {
479        self.0.borrow().items.summary().count
480    }
481
482    /// Whether the list is scrolled to the end, or `None` if the list is
483    /// not scrollable or the total content height is not yet known.
484    pub fn is_scrolled_to_end(&self) -> Option<bool> {
485        let state = self.0.borrow();
486        let bounds = state.last_layout_bounds?;
487        let summary = state.items.summary();
488        if summary.has_unknown_height {
489            return None;
490        }
491        let padding = state.last_padding.unwrap_or_default();
492        let content_height = summary.height + padding.top + padding.bottom;
493        let scroll_max = (content_height - bounds.size.height).max(px(0.));
494        if scroll_max <= px(0.) {
495            return None;
496        }
497        let scroll_top = state.scroll_top(&state.logical_scroll_top());
498        Some(scroll_top >= scroll_max)
499    }
500
501    /// Inform the list state that the items in `old_range` have been replaced
502    /// by `count` new items that must be recalculated.
503    pub fn splice(&self, old_range: Range<usize>, count: usize) {
504        self.splice_focusable(old_range, (0..count).map(|_| None))
505    }
506
507    /// Register with the list state that the items in `old_range` have been replaced
508    /// by new items. As opposed to [`Self::splice`], this method allows an iterator of optional focus handles
509    /// to be supplied to properly integrate with items in the list that can be focused. If a focused item
510    /// is scrolled out of view, the list will continue to render it to allow keyboard interaction.
511    pub fn splice_focusable(
512        &self,
513        old_range: Range<usize>,
514        focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
515    ) {
516        let state = &mut *self.0.borrow_mut();
517
518        let mut old_items = state.items.cursor::<Count>(());
519        let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right);
520        old_items.seek_forward(&Count(old_range.end), Bias::Right);
521
522        let mut spliced_count = 0;
523        new_items.extend(
524            focus_handles.into_iter().map(|focus_handle| {
525                spliced_count += 1;
526                ListItem::Unmeasured {
527                    size_hint: None,
528                    focus_handle,
529                }
530            }),
531            (),
532        );
533        new_items.append(old_items.suffix(), ());
534        drop(old_items);
535        state.items = new_items;
536
537        if let Some(ListOffset {
538            item_ix,
539            offset_in_item,
540        }) = state.logical_scroll_top.as_mut()
541        {
542            if old_range.contains(item_ix) {
543                *item_ix = old_range.start;
544                *offset_in_item = px(0.);
545            } else if old_range.end <= *item_ix {
546                *item_ix = *item_ix - (old_range.end - old_range.start) + spliced_count;
547            }
548        }
549    }
550
551    /// Set a handler that will be called when the list is scrolled.
552    pub fn set_scroll_handler(
553        &self,
554        handler: impl FnMut(&ListScrollEvent, &mut Window, &mut App) + 'static,
555    ) {
556        self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
557    }
558
559    /// Get the current scroll offset, in terms of the list's items.
560    pub fn logical_scroll_top(&self) -> ListOffset {
561        self.0.borrow().logical_scroll_top()
562    }
563
564    /// Scroll the list by the given offset
565    pub fn scroll_by(&self, distance: Pixels) {
566        if distance == px(0.) {
567            return;
568        }
569
570        let current_offset = self.logical_scroll_top();
571        let state = &mut *self.0.borrow_mut();
572
573        if distance < px(0.) {
574            state.follow_state.stop_following();
575        }
576
577        let mut cursor = state.items.cursor::<ListItemSummary>(());
578        cursor.seek(&Count(current_offset.item_ix), Bias::Right);
579
580        let start_pixel_offset = cursor.start().height + current_offset.offset_in_item;
581        let new_pixel_offset = (start_pixel_offset + distance).max(px(0.));
582        if new_pixel_offset > start_pixel_offset {
583            cursor.seek_forward(&Height(new_pixel_offset), Bias::Right);
584        } else {
585            cursor.seek(&Height(new_pixel_offset), Bias::Right);
586        }
587
588        let scroll_top = ListOffset {
589            item_ix: cursor.start().count,
590            offset_in_item: new_pixel_offset - cursor.start().height,
591        };
592        drop(cursor);
593        state.rebase_pending_scroll(scroll_top);
594        state.logical_scroll_top = Some(scroll_top);
595    }
596
597    /// Scroll the list to the very end (past the last item).
598    ///
599    /// Unlike [`scroll_to_reveal_item`], this uses the total item count as the
600    /// anchor, so the list's layout pass will walk backwards from the end and
601    /// always show the bottom of the last item — even when that item is still
602    /// growing (e.g. during streaming).
603    pub fn scroll_to_end(&self) {
604        let state = &mut *self.0.borrow_mut();
605        let item_count = state.items.summary().count;
606        state.pending_scroll = None;
607        state.logical_scroll_top = Some(ListOffset {
608            item_ix: item_count,
609            offset_in_item: px(0.),
610        });
611    }
612
613    /// Set the follow mode for the list. In `Tail` mode, the list
614    /// will auto-scroll to the end and re-engage after the user
615    /// scrolls back to the bottom. In `Normal` mode, no automatic
616    /// following occurs.
617    pub fn set_follow_mode(&self, mode: FollowMode) {
618        let state = &mut *self.0.borrow_mut();
619
620        match mode {
621            FollowMode::Normal => {
622                state.follow_state = FollowState::Normal;
623            }
624            FollowMode::Tail => {
625                state.follow_state = FollowState::Tail { is_following: true };
626                if matches!(mode, FollowMode::Tail) {
627                    let item_count = state.items.summary().count;
628                    state.logical_scroll_top = Some(ListOffset {
629                        item_ix: item_count,
630                        offset_in_item: px(0.),
631                    });
632                }
633            }
634        }
635    }
636
637    /// Returns whether the list is currently actively following the
638    /// tail (snapping to the end on each layout).
639    pub fn is_following_tail(&self) -> bool {
640        matches!(
641            self.0.borrow().follow_state,
642            FollowState::Tail { is_following: true }
643        )
644    }
645
646    /// Scroll the list to the given offset
647    pub fn scroll_to(&self, mut scroll_top: ListOffset) {
648        let state = &mut *self.0.borrow_mut();
649        let item_count = state.items.summary().count;
650        if scroll_top.item_ix >= item_count {
651            scroll_top.item_ix = item_count;
652            scroll_top.offset_in_item = px(0.);
653        }
654
655        if scroll_top.item_ix < item_count {
656            state.follow_state.stop_following();
657        }
658
659        state.rebase_pending_scroll(scroll_top);
660        state.logical_scroll_top = Some(scroll_top);
661    }
662
663    /// Scroll the list to the given item, such that the item is fully visible.
664    pub fn scroll_to_reveal_item(&self, ix: usize) {
665        let state = &mut *self.0.borrow_mut();
666
667        let mut scroll_top = state.logical_scroll_top();
668        let height = state
669            .last_layout_bounds
670            .map_or(px(0.), |bounds| bounds.size.height);
671        let padding = state.last_padding.unwrap_or_default();
672
673        if ix <= scroll_top.item_ix {
674            scroll_top.item_ix = ix;
675            scroll_top.offset_in_item = px(0.);
676        } else {
677            let mut cursor = state.items.cursor::<ListItemSummary>(());
678            cursor.seek(&Count(ix + 1), Bias::Right);
679            let bottom = cursor.start().height + padding.top;
680            let goal_top = px(0.).max(bottom - height + padding.bottom);
681
682            cursor.seek(&Height(goal_top), Bias::Left);
683            let start_ix = cursor.start().count;
684            let start_item_top = cursor.start().height;
685
686            if start_ix >= scroll_top.item_ix {
687                scroll_top.item_ix = start_ix;
688                scroll_top.offset_in_item = goal_top - start_item_top;
689            }
690        }
691
692        state.rebase_pending_scroll(scroll_top);
693        state.logical_scroll_top = Some(scroll_top);
694    }
695
696    /// Get the bounds for the given item in window coordinates, if it's
697    /// been rendered.
698    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
699        let state = &*self.0.borrow();
700
701        let bounds = state.last_layout_bounds.unwrap_or_default();
702        let padding = state.last_padding.unwrap_or_default();
703        let scroll_top = state.logical_scroll_top();
704        if ix < scroll_top.item_ix {
705            return None;
706        }
707
708        let mut cursor = state.items.cursor::<Dimensions<Count, Height>>(());
709        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
710
711        let scroll_top = cursor.start().1.0 + scroll_top.offset_in_item;
712
713        cursor.seek_forward(&Count(ix), Bias::Right);
714        if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
715            let &Dimensions(Count(count), Height(top), _) = cursor.start();
716            if count == ix {
717                let top = bounds.top() + padding.top + top - scroll_top;
718                return Some(Bounds::from_corners(
719                    point(bounds.left() + padding.left, top),
720                    point(bounds.right() - padding.right, top + size.height),
721                ));
722            }
723        }
724        None
725    }
726
727    /// Call this method when the user starts dragging the scrollbar.
728    ///
729    /// This will prevent the height reported to the scrollbar from changing during the drag
730    /// as items in the overdraw get measured, and help offset scroll position changes accordingly.
731    pub fn scrollbar_drag_started(&self) {
732        let mut state = self.0.borrow_mut();
733        state.scrollbar_drag_start_height = Some(state.items.summary().height);
734    }
735
736    /// Called when the user stops dragging the scrollbar.
737    ///
738    /// See `scrollbar_drag_started`.
739    pub fn scrollbar_drag_ended(&self) {
740        self.0.borrow_mut().scrollbar_drag_start_height.take();
741    }
742
743    /// Returns `true` if the scrollbar is currently being dragged.
744    ///
745    /// This is set between [`scrollbar_drag_started`](Self::scrollbar_drag_started)
746    /// and [`scrollbar_drag_ended`](Self::scrollbar_drag_ended) calls. Useful for
747    /// consumers that need to distinguish scrollbar drags from wheel/trackpad scrolls,
748    /// e.g. to suppress auto-scroll behavior during manual positioning.
749    pub fn is_scrollbar_dragging(&self) -> bool {
750        self.0.borrow().scrollbar_drag_start_height.is_some()
751    }
752
753    /// Set the offset from the scrollbar
754    pub fn set_offset_from_scrollbar(&self, point: Point<Pixels>) {
755        self.0.borrow_mut().set_offset_from_scrollbar(point);
756    }
757
758    /// Returns the maximum scroll offset according to the items we have measured.
759    /// This value remains constant while dragging to prevent the scrollbar from moving away unexpectedly.
760    pub fn max_offset_for_scrollbar(&self) -> Point<Pixels> {
761        let state = self.0.borrow();
762        point(Pixels::ZERO, state.max_scroll_offset())
763    }
764
765    /// Returns the current scroll offset adjusted for the scrollbar.
766    ///
767    /// The returned offset has a negative `y` component representing
768    /// how far the content has scrolled.
769    pub fn scroll_px_offset_for_scrollbar(&self) -> Point<Pixels> {
770        let state = &self.0.borrow();
771
772        if state.logical_scroll_top.is_none() && state.alignment == ListAlignment::Bottom {
773            return Point::new(px(0.), -state.max_scroll_offset());
774        }
775
776        let logical_scroll_top = state.logical_scroll_top();
777
778        let mut cursor = state.items.cursor::<ListItemSummary>(());
779        let summary: ListItemSummary =
780            cursor.summary(&Count(logical_scroll_top.item_ix), Bias::Right);
781        let offset = summary.height + logical_scroll_top.offset_in_item;
782
783        Point::new(px(0.), -offset)
784    }
785
786    /// Return the bounds of the viewport in pixels.
787    pub fn viewport_bounds(&self) -> Bounds<Pixels> {
788        self.0.borrow().last_layout_bounds.unwrap_or_default()
789    }
790
791    /// Returns whether the item is entirely above the viewport, or `None` if
792    /// the list has not measured enough layout to know.
793    ///
794    /// A zero-height viewport still yields a definitive answer: callers may
795    /// size sibling UI based on this query (potentially squeezing the list
796    /// itself to zero height), so returning `None` in that case would make
797    /// the answer oscillate from frame to frame.
798    pub fn item_is_above_viewport(&self, ix: usize) -> Option<bool> {
799        let viewport_bounds = self.0.borrow().last_layout_bounds?;
800
801        let scroll_top = self.logical_scroll_top();
802        if ix < scroll_top.item_ix {
803            // Rows before the logical scroll top have no item bounds, but
804            // their position relative to the viewport is known from scroll state.
805            return Some(true);
806        }
807
808        let item_bounds = self.bounds_for_item(ix)?;
809        Some(item_bounds.bottom() <= viewport_bounds.top())
810    }
811
812    /// Returns whether the item is entirely below the viewport, or `None` if
813    /// the list has not measured enough layout to know.
814    ///
815    /// See [`Self::item_is_above_viewport`] for why a zero-height viewport
816    /// still yields a definitive answer.
817    pub fn item_is_below_viewport(&self, ix: usize) -> Option<bool> {
818        let viewport_bounds = self.0.borrow().last_layout_bounds?;
819
820        let scroll_top = self.logical_scroll_top();
821        if ix < scroll_top.item_ix {
822            // Rows before the logical scroll top have no item bounds, but
823            // their position relative to the viewport is known from scroll state.
824            return Some(false);
825        }
826
827        let item_bounds = self.bounds_for_item(ix)?;
828        Some(item_bounds.top() >= viewport_bounds.bottom())
829    }
830}
831
832impl StateInner {
833    /// Re-anchor a pending scroll adjustment from a remeasure onto a newly set
834    /// scroll position, so it clamps to the remeasured item's new height on
835    /// the next layout instead of reverting the scroll.
836    fn rebase_pending_scroll(&mut self, scroll_top: ListOffset) {
837        let Some(pending) = self.pending_scroll.take() else {
838            return;
839        };
840        if scroll_top.item_ix >= self.items.summary().count {
841            return;
842        }
843
844        self.pending_scroll = match pending {
845            PendingScroll::Absolute { .. } => Some(PendingScroll::Absolute {
846                item_ix: scroll_top.item_ix,
847                offset: scroll_top.offset_in_item,
848            }),
849            PendingScroll::Proportional(_) => {
850                let mut cursor = self.items.cursor::<Count>(());
851                cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
852                cursor
853                    .item()
854                    .and_then(|item| item.size_hint())
855                    .filter(|size| size.height.0 > 0.0)
856                    .map(|size| {
857                        PendingScroll::Proportional(PendingScrollFraction {
858                            item_ix: scroll_top.item_ix,
859                            fraction: (scroll_top.offset_in_item.0 / size.height.0).clamp(0.0, 1.0),
860                        })
861                    })
862            }
863        };
864    }
865
866    fn max_scroll_offset(&self) -> Pixels {
867        let bounds = self.last_layout_bounds.unwrap_or_default();
868        let height = self
869            .scrollbar_drag_start_height
870            .unwrap_or_else(|| self.items.summary().height);
871        let padding = self.last_padding.unwrap_or_default();
872        (height + padding.top + padding.bottom - bounds.size.height).max(px(0.))
873    }
874
875    fn visible_range(
876        items: &SumTree<ListItem>,
877        height: Pixels,
878        scroll_top: &ListOffset,
879    ) -> Range<usize> {
880        let mut cursor = items.cursor::<ListItemSummary>(());
881        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
882        let start_y = cursor.start().height + scroll_top.offset_in_item;
883        cursor.seek_forward(&Height(start_y + height), Bias::Left);
884        scroll_top.item_ix..cursor.start().count + 1
885    }
886
887    fn scroll(
888        &mut self,
889        scroll_top: &ListOffset,
890        height: Pixels,
891        delta: Point<Pixels>,
892        current_view: EntityId,
893        window: &mut Window,
894        cx: &mut App,
895    ) {
896        // Drop scroll events after a reset, since we can't calculate
897        // the new logical scroll top without the item heights
898        if self.reset {
899            return;
900        }
901
902        let padding = self.last_padding.unwrap_or_default();
903        let scroll_max =
904            (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
905        let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
906            .max(px(0.))
907            .min(scroll_max);
908
909        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
910            self.pending_scroll = None;
911            self.logical_scroll_top = None;
912        } else {
913            let (start, ..) =
914                self.items
915                    .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
916            let scroll_top = ListOffset {
917                item_ix: start.count,
918                offset_in_item: new_scroll_top - start.height,
919            };
920            // The user's scroll supersedes the position stashed by a
921            // remeasure; re-anchor the pending adjustment so it doesn't revert
922            // this scroll on the next layout.
923            self.rebase_pending_scroll(scroll_top);
924            self.logical_scroll_top = Some(scroll_top);
925        }
926
927        if delta.y > px(0.) {
928            self.follow_state.stop_following();
929        }
930
931        if let Some(handler) = self.scroll_handler.as_mut() {
932            let visible_range = Self::visible_range(&self.items, height, scroll_top);
933            handler(
934                &ListScrollEvent {
935                    visible_range,
936                    count: self.items.summary().count,
937                    is_scrolled: self.logical_scroll_top.is_some(),
938                    is_following_tail: matches!(
939                        self.follow_state,
940                        FollowState::Tail { is_following: true }
941                    ),
942                },
943                window,
944                cx,
945            );
946        }
947
948        cx.notify(current_view);
949    }
950
951    fn logical_scroll_top(&self) -> ListOffset {
952        self.logical_scroll_top
953            .unwrap_or_else(|| match self.alignment {
954                ListAlignment::Top => ListOffset {
955                    item_ix: 0,
956                    offset_in_item: px(0.),
957                },
958                ListAlignment::Bottom => ListOffset {
959                    item_ix: self.items.summary().count,
960                    offset_in_item: px(0.),
961                },
962            })
963    }
964
965    fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
966        let (start, ..) = self.items.find::<ListItemSummary, _>(
967            (),
968            &Count(logical_scroll_top.item_ix),
969            Bias::Right,
970        );
971        start.height + logical_scroll_top.offset_in_item
972    }
973
974    fn layout_all_items(
975        &mut self,
976        available_width: Pixels,
977        render_item: &mut RenderItemFn,
978        window: &mut Window,
979        cx: &mut App,
980    ) {
981        match &mut self.measuring_behavior {
982            ListMeasuringBehavior::Visible => {
983                return;
984            }
985            ListMeasuringBehavior::Measure(has_measured) => {
986                if *has_measured {
987                    return;
988                }
989                *has_measured = true;
990            }
991        }
992
993        let mut cursor = self.items.cursor::<Count>(());
994        let available_item_space = size(
995            AvailableSpace::Definite(available_width),
996            AvailableSpace::MinContent,
997        );
998
999        let mut measured_items = Vec::default();
1000
1001        for (ix, item) in cursor.enumerate() {
1002            let size = item.size().unwrap_or_else(|| {
1003                let mut element = render_item(ix, window, cx);
1004                element.layout_as_root(available_item_space, window, cx)
1005            });
1006
1007            measured_items.push(ListItem::Measured {
1008                size,
1009                focus_handle: item.focus_handle(),
1010            });
1011        }
1012
1013        self.items = SumTree::from_iter(measured_items, ());
1014    }
1015
1016    fn layout_items(
1017        &mut self,
1018        available_width: Option<Pixels>,
1019        available_height: Pixels,
1020        padding: &Edges<Pixels>,
1021        render_item: &mut RenderItemFn,
1022        window: &mut Window,
1023        cx: &mut App,
1024    ) -> LayoutItemsResponse {
1025        let old_items = self.items.clone();
1026        let mut measured_items = VecDeque::new();
1027        let mut item_layouts = VecDeque::new();
1028        let mut rendered_height = padding.top;
1029        let mut max_item_width = px(0.);
1030        let mut scroll_top = self.logical_scroll_top();
1031
1032        if self.follow_state.is_following() {
1033            scroll_top = ListOffset {
1034                item_ix: self.items.summary().count,
1035                offset_in_item: px(0.),
1036            };
1037            self.logical_scroll_top = Some(scroll_top);
1038        }
1039
1040        let mut rendered_focused_item = false;
1041
1042        let available_item_space = size(
1043            available_width.map_or(AvailableSpace::MaxContent, |width| {
1044                AvailableSpace::Definite(width)
1045            }),
1046            AvailableSpace::MinContent,
1047        );
1048
1049        let mut cursor = old_items.cursor::<Count>(());
1050
1051        // Render items after the scroll top, including those in the trailing overdraw
1052        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1053        for (ix, item) in cursor.by_ref().enumerate() {
1054            let visible_height = rendered_height - scroll_top.offset_in_item;
1055            if visible_height >= available_height + self.overdraw {
1056                break;
1057            }
1058
1059            // Use the previously cached height and focus handle if available
1060            let mut size = item.size();
1061
1062            // If we're within the visible area or the height wasn't cached, render and measure the item's element
1063            if visible_height < available_height || size.is_none() {
1064                let item_index = scroll_top.item_ix + ix;
1065                let mut element = render_item(item_index, window, cx);
1066                let element_size = element.layout_as_root(available_item_space, window, cx);
1067                size = Some(element_size);
1068
1069                // If there's a pending scroll adjustment for the scroll-top
1070                // item, apply it.
1071                if ix == 0 {
1072                    if let Some(pending_scroll) = self.pending_scroll.take() {
1073                        match pending_scroll {
1074                            PendingScroll::Absolute { item_ix, offset }
1075                                if item_ix == scroll_top.item_ix =>
1076                            {
1077                                scroll_top.offset_in_item = offset.min(element_size.height);
1078                                self.logical_scroll_top = Some(scroll_top);
1079                            }
1080                            PendingScroll::Proportional(pending_scroll)
1081                                if pending_scroll.item_ix == scroll_top.item_ix =>
1082                            {
1083                                // Ensuring proportional scroll position is
1084                                // maintained after re-measuring.
1085                                scroll_top.offset_in_item =
1086                                    Pixels(pending_scroll.fraction * element_size.height.0);
1087                                self.logical_scroll_top = Some(scroll_top);
1088                            }
1089                            _ => {}
1090                        }
1091                    }
1092                }
1093
1094                if visible_height < available_height {
1095                    item_layouts.push_back(ItemLayout {
1096                        index: item_index,
1097                        element,
1098                        size: element_size,
1099                    });
1100                    if item.contains_focused(window, cx) {
1101                        rendered_focused_item = true;
1102                    }
1103                }
1104            }
1105
1106            let size = size.unwrap();
1107            rendered_height += size.height;
1108            max_item_width = max_item_width.max(size.width);
1109            measured_items.push_back(ListItem::Measured {
1110                size,
1111                focus_handle: item.focus_handle(),
1112            });
1113        }
1114        rendered_height += padding.bottom;
1115
1116        // Prepare to start walking upward from the item at the scroll top.
1117        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1118
1119        // If the rendered items do not fill the visible region, then adjust
1120        // the scroll top upward.
1121        if rendered_height - scroll_top.offset_in_item < available_height {
1122            while rendered_height < available_height {
1123                cursor.prev();
1124                if let Some(item) = cursor.item() {
1125                    let item_index = cursor.start().0;
1126                    let mut element = render_item(item_index, window, cx);
1127                    let element_size = element.layout_as_root(available_item_space, window, cx);
1128                    let focus_handle = item.focus_handle();
1129                    rendered_height += element_size.height;
1130                    measured_items.push_front(ListItem::Measured {
1131                        size: element_size,
1132                        focus_handle,
1133                    });
1134                    item_layouts.push_front(ItemLayout {
1135                        index: item_index,
1136                        element,
1137                        size: element_size,
1138                    });
1139                    if item.contains_focused(window, cx) {
1140                        rendered_focused_item = true;
1141                    }
1142                } else {
1143                    break;
1144                }
1145            }
1146
1147            scroll_top = ListOffset {
1148                item_ix: cursor.start().0,
1149                offset_in_item: rendered_height - available_height,
1150            };
1151
1152            match self.alignment {
1153                ListAlignment::Top => {
1154                    scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
1155                    self.logical_scroll_top = Some(scroll_top);
1156                }
1157                ListAlignment::Bottom => {
1158                    scroll_top = ListOffset {
1159                        item_ix: cursor.start().0,
1160                        offset_in_item: rendered_height - available_height,
1161                    };
1162                    self.logical_scroll_top = None;
1163                }
1164            };
1165        }
1166
1167        // Measure items in the leading overdraw
1168        let mut leading_overdraw = scroll_top.offset_in_item;
1169        while leading_overdraw < self.overdraw {
1170            cursor.prev();
1171            if let Some(item) = cursor.item() {
1172                let size = if let ListItem::Measured { size, .. } = item {
1173                    *size
1174                } else {
1175                    let mut element = render_item(cursor.start().0, window, cx);
1176                    element.layout_as_root(available_item_space, window, cx)
1177                };
1178
1179                leading_overdraw += size.height;
1180                measured_items.push_front(ListItem::Measured {
1181                    size,
1182                    focus_handle: item.focus_handle(),
1183                });
1184            } else {
1185                break;
1186            }
1187        }
1188
1189        let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
1190        let mut cursor = old_items.cursor::<Count>(());
1191        let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right);
1192        new_items.extend(measured_items, ());
1193        cursor.seek(&Count(measured_range.end), Bias::Right);
1194        new_items.append(cursor.suffix(), ());
1195        self.items = new_items;
1196
1197        // If follow_tail mode is on but the user scrolled away
1198        // (is_following is false), check whether the current scroll
1199        // position has returned to the bottom.
1200        if self.follow_state.has_stopped_following() {
1201            let padding = self.last_padding.unwrap_or_default();
1202            let total_height = self.items.summary().height + padding.top + padding.bottom;
1203            let scroll_offset = self.scroll_top(&scroll_top);
1204            if scroll_offset + available_height >= total_height - px(1.0) {
1205                self.follow_state.start_following();
1206            }
1207        }
1208
1209        // If none of the visible items are focused, check if an off-screen item is focused
1210        // and include it to be rendered after the visible items so keyboard interaction continues
1211        // to work for it.
1212        if !rendered_focused_item {
1213            let mut cursor = self
1214                .items
1215                .filter::<_, Count>((), |summary| summary.has_focus_handles);
1216            cursor.next();
1217            while let Some(item) = cursor.item() {
1218                if item.contains_focused(window, cx) {
1219                    let item_index = cursor.start().0;
1220                    let mut element = render_item(cursor.start().0, window, cx);
1221                    let size = element.layout_as_root(available_item_space, window, cx);
1222                    item_layouts.push_back(ItemLayout {
1223                        index: item_index,
1224                        element,
1225                        size,
1226                    });
1227                    break;
1228                }
1229                cursor.next();
1230            }
1231        }
1232
1233        LayoutItemsResponse {
1234            max_item_width,
1235            scroll_top,
1236            item_layouts,
1237        }
1238    }
1239
1240    fn prepaint_items(
1241        &mut self,
1242        bounds: Bounds<Pixels>,
1243        padding: Edges<Pixels>,
1244        autoscroll: bool,
1245        render_item: &mut RenderItemFn,
1246        window: &mut Window,
1247        cx: &mut App,
1248    ) -> Result<LayoutItemsResponse, ListOffset> {
1249        let item_width = bounds.size.width - (padding.left + padding.right);
1250        window.transact(|window| {
1251            match self.measuring_behavior {
1252                ListMeasuringBehavior::Measure(has_measured) if !has_measured => {
1253                    self.layout_all_items(item_width, render_item, window, cx);
1254                }
1255                _ => {}
1256            }
1257
1258            let mut layout_response = self.layout_items(
1259                Some(item_width),
1260                bounds.size.height,
1261                &padding,
1262                render_item,
1263                window,
1264                cx,
1265            );
1266
1267            // Avoid honoring autoscroll requests from elements other than our children.
1268            window.take_autoscroll();
1269
1270            // Only paint the visible items, if there is actually any space for them (taking padding into account)
1271            if bounds.size.height > padding.top + padding.bottom {
1272                let mut item_origin = bounds.origin + Point::new(padding.left, padding.top);
1273                item_origin.y -= layout_response.scroll_top.offset_in_item;
1274                for item in &mut layout_response.item_layouts {
1275                    window.with_content_mask(Some(ContentMask { bounds }), |window| {
1276                        item.element.prepaint_at(item_origin, window, cx);
1277                    });
1278
1279                    if let Some(autoscroll_bounds) = window.take_autoscroll()
1280                        && autoscroll
1281                    {
1282                        if autoscroll_bounds.top() < bounds.top() {
1283                            let mut item_ix = item.index;
1284                            let mut offset_in_item = autoscroll_bounds.top() - item_origin.y;
1285
1286                            // The requested top can sit above this item's own
1287                            // top. Walk into earlier items so the offset stays
1288                            // non-negative and no blank space appears above the
1289                            // list.
1290                            if offset_in_item < Pixels::ZERO {
1291                                let mut cursor = self.items.cursor::<Count>(());
1292                                cursor.seek(&Count(item_ix), Bias::Right);
1293                                while offset_in_item < Pixels::ZERO {
1294                                    cursor.prev();
1295                                    let Some(prev_item) = cursor.item() else {
1296                                        offset_in_item = Pixels::ZERO;
1297                                        break;
1298                                    };
1299                                    let size = prev_item.size().unwrap_or_else(|| {
1300                                        let mut element = render_item(cursor.start().0, window, cx);
1301                                        let item_available_size =
1302                                            size(item_width.into(), AvailableSpace::MinContent);
1303                                        element.layout_as_root(item_available_size, window, cx)
1304                                    });
1305                                    item_ix = cursor.start().0;
1306                                    offset_in_item += size.height;
1307                                }
1308                            }
1309
1310                            return Err(ListOffset {
1311                                item_ix,
1312                                offset_in_item,
1313                            });
1314                        } else if autoscroll_bounds.bottom() > bounds.bottom() {
1315                            let mut cursor = self.items.cursor::<Count>(());
1316                            cursor.seek(&Count(item.index), Bias::Right);
1317                            let mut height = bounds.size.height - padding.top - padding.bottom;
1318
1319                            // Account for the height of the element down until the autoscroll bottom.
1320                            height -= autoscroll_bounds.bottom() - item_origin.y;
1321
1322                            // Keep decreasing the scroll top until we fill all the available space.
1323                            while height > Pixels::ZERO {
1324                                cursor.prev();
1325                                let Some(item) = cursor.item() else { break };
1326
1327                                let size = item.size().unwrap_or_else(|| {
1328                                    let mut item = render_item(cursor.start().0, window, cx);
1329                                    let item_available_size =
1330                                        size(item_width.into(), AvailableSpace::MinContent);
1331                                    item.layout_as_root(item_available_size, window, cx)
1332                                });
1333                                height -= size.height;
1334                            }
1335
1336                            return Err(ListOffset {
1337                                item_ix: cursor.start().0,
1338                                offset_in_item: if height < Pixels::ZERO {
1339                                    -height
1340                                } else {
1341                                    Pixels::ZERO
1342                                },
1343                            });
1344                        }
1345                    }
1346
1347                    item_origin.y += item.size.height;
1348                }
1349            } else {
1350                layout_response.item_layouts.clear();
1351            }
1352
1353            Ok(layout_response)
1354        })
1355    }
1356
1357    // Scrollbar support
1358
1359    fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
1360        let Some(bounds) = self.last_layout_bounds else {
1361            return;
1362        };
1363        let height = bounds.size.height;
1364
1365        let padding = self.last_padding.unwrap_or_default();
1366        // Scrollbar drag positions are computed from the content height
1367        // captured at drag start, so map them back using the same height.
1368        let content_height = self
1369            .scrollbar_drag_start_height
1370            .unwrap_or_else(|| self.items.summary().height);
1371        let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
1372        let new_scroll_top = (-point.y).max(px(0.)).min(scroll_max);
1373
1374        // If content grew during the drag, the frozen bottom is below the
1375        // live bottom. Treat dragging to the frozen end as resuming tail follow.
1376        let dragged_to_end =
1377            scroll_max > px(0.) && new_scroll_top >= (scroll_max - px(1.0)).max(px(0.));
1378        if dragged_to_end && matches!(self.follow_state, FollowState::Tail { .. }) {
1379            self.follow_state = FollowState::Tail { is_following: true };
1380            let item_count = self.items.summary().count;
1381            self.pending_scroll = None;
1382            self.logical_scroll_top = Some(ListOffset {
1383                item_ix: item_count,
1384                offset_in_item: px(0.),
1385            });
1386            return;
1387        }
1388
1389        self.follow_state.stop_following();
1390
1391        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
1392            self.pending_scroll = None;
1393            self.logical_scroll_top = None;
1394        } else {
1395            let (start, _, _) =
1396                self.items
1397                    .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
1398
1399            let scroll_top = ListOffset {
1400                item_ix: start.count,
1401                offset_in_item: new_scroll_top - start.height,
1402            };
1403            self.rebase_pending_scroll(scroll_top);
1404            self.logical_scroll_top = Some(scroll_top);
1405        }
1406    }
1407}
1408
1409impl std::fmt::Debug for ListItem {
1410    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1411        match self {
1412            Self::Unmeasured { .. } => write!(f, "Unrendered"),
1413            Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
1414        }
1415    }
1416}
1417
1418/// An offset into the list's items, in terms of the item index and the number
1419/// of pixels off the top left of the item.
1420#[derive(Debug, Clone, Copy, Default)]
1421pub struct ListOffset {
1422    /// The index of an item in the list
1423    pub item_ix: usize,
1424    /// The number of pixels to offset from the item index.
1425    pub offset_in_item: Pixels,
1426}
1427
1428impl Element for List {
1429    type RequestLayoutState = ();
1430    type PrepaintState = ListPrepaintState;
1431
1432    fn id(&self) -> Option<crate::ElementId> {
1433        None
1434    }
1435
1436    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1437        None
1438    }
1439
1440    fn request_layout(
1441        &mut self,
1442        _id: Option<&GlobalElementId>,
1443        _inspector_id: Option<&InspectorElementId>,
1444        window: &mut Window,
1445        cx: &mut App,
1446    ) -> (crate::LayoutId, Self::RequestLayoutState) {
1447        let layout_id = match self.sizing_behavior {
1448            ListSizingBehavior::Infer => {
1449                let mut style = Style::default();
1450                style.overflow.y = Overflow::Scroll;
1451                style.refine(&self.style);
1452                window.with_text_style(style.text_style().cloned(), |window| {
1453                    let state = &mut *self.state.0.borrow_mut();
1454
1455                    let available_height = if let Some(last_bounds) = state.last_layout_bounds {
1456                        last_bounds.size.height
1457                    } else {
1458                        // If we don't have the last layout bounds (first render),
1459                        // we might just use the overdraw value as the available height to layout enough items.
1460                        state.overdraw
1461                    };
1462                    let padding = content_insets(
1463                        &style,
1464                        state.last_layout_bounds.unwrap_or_default().size,
1465                        window.rem_size(),
1466                    );
1467
1468                    let layout_response = state.layout_items(
1469                        None,
1470                        available_height,
1471                        &padding,
1472                        &mut self.render_item,
1473                        window,
1474                        cx,
1475                    );
1476                    let max_element_width = layout_response.max_item_width;
1477
1478                    let summary = state.items.summary();
1479                    let total_height = summary.height;
1480
1481                    window.request_measured_layout(
1482                        style,
1483                        move |known_dimensions, available_space, _window, _cx| {
1484                            let width =
1485                                known_dimensions
1486                                    .width
1487                                    .unwrap_or(match available_space.width {
1488                                        AvailableSpace::Definite(x) => x,
1489                                        AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1490                                            max_element_width
1491                                        }
1492                                    });
1493                            let height = match available_space.height {
1494                                AvailableSpace::Definite(height) => total_height.min(height),
1495                                AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1496                                    total_height
1497                                }
1498                            };
1499                            size(width, height)
1500                        },
1501                    )
1502                })
1503            }
1504            ListSizingBehavior::Auto => {
1505                let mut style = Style::default();
1506                style.refine(&self.style);
1507                window.with_text_style(style.text_style().cloned(), |window| {
1508                    window.request_layout(style, None, cx)
1509                })
1510            }
1511        };
1512        (layout_id, ())
1513    }
1514
1515    fn prepaint(
1516        &mut self,
1517        _id: Option<&GlobalElementId>,
1518        _inspector_id: Option<&InspectorElementId>,
1519        bounds: Bounds<Pixels>,
1520        _: &mut Self::RequestLayoutState,
1521        window: &mut Window,
1522        cx: &mut App,
1523    ) -> ListPrepaintState {
1524        let state = &mut *self.state.0.borrow_mut();
1525        state.reset = false;
1526
1527        let mut style = Style::default();
1528        style.refine(&self.style);
1529
1530        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1531
1532        let padding = content_insets(&style, bounds.size, window.rem_size());
1533
1534        // If the width of the list or the list content insets have changed,
1535        // invalidate all cached item heights
1536        let last_item_width =
1537            state
1538                .last_layout_bounds
1539                .zip(state.last_padding)
1540                .map(|(last_bounds, last_padding)| {
1541                    last_bounds.size.width - (last_padding.left + last_padding.right)
1542                });
1543        if last_item_width
1544            .is_none_or(|width| width != bounds.size.width - (padding.left + padding.right))
1545        {
1546            let new_items = SumTree::from_iter(
1547                state.items.iter().map(|item| ListItem::Unmeasured {
1548                    size_hint: None,
1549                    focus_handle: item.focus_handle(),
1550                }),
1551                (),
1552            );
1553
1554            state.items = new_items;
1555            state.measuring_behavior.reset();
1556        }
1557
1558        let layout =
1559            match state.prepaint_items(bounds, padding, true, &mut self.render_item, window, cx) {
1560                Ok(layout) => layout,
1561                Err(autoscroll_request) => {
1562                    state.logical_scroll_top = Some(autoscroll_request);
1563                    state
1564                        .prepaint_items(bounds, padding, false, &mut self.render_item, window, cx)
1565                        .unwrap()
1566                }
1567            };
1568
1569        state.last_layout_bounds = Some(bounds);
1570        state.last_padding = Some(padding);
1571        ListPrepaintState { hitbox, layout }
1572    }
1573
1574    fn paint(
1575        &mut self,
1576        _id: Option<&GlobalElementId>,
1577        _inspector_id: Option<&InspectorElementId>,
1578        bounds: Bounds<crate::Pixels>,
1579        _: &mut Self::RequestLayoutState,
1580        prepaint: &mut Self::PrepaintState,
1581        window: &mut Window,
1582        cx: &mut App,
1583    ) {
1584        let current_view = window.current_view();
1585        window.with_content_mask(Some(ContentMask { bounds }), |window| {
1586            for item in &mut prepaint.layout.item_layouts {
1587                item.element.paint(window, cx);
1588            }
1589        });
1590
1591        let list_state = self.state.clone();
1592        let height = bounds.size.height;
1593        let scroll_top = prepaint.layout.scroll_top;
1594        let hitbox_id = prepaint.hitbox.id;
1595        let mut accumulated_scroll_delta = ScrollDelta::default();
1596        window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
1597            if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
1598                accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
1599                let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1600                list_state.0.borrow_mut().scroll(
1601                    &scroll_top,
1602                    height,
1603                    pixel_delta,
1604                    current_view,
1605                    window,
1606                    cx,
1607                )
1608            }
1609        });
1610    }
1611}
1612
1613fn content_insets(style: &Style, size: Size<Pixels>, rem_size: Pixels) -> Edges<Pixels> {
1614    let padding = style.padding.to_pixels(size.into(), rem_size);
1615    let border = style.border_widths.to_pixels(rem_size);
1616
1617    padding + border
1618}
1619
1620impl IntoElement for List {
1621    type Element = Self;
1622
1623    fn into_element(self) -> Self::Element {
1624        self
1625    }
1626}
1627
1628impl Styled for List {
1629    fn style(&mut self) -> &mut StyleRefinement {
1630        &mut self.style
1631    }
1632}
1633
1634impl sum_tree::Item for ListItem {
1635    type Summary = ListItemSummary;
1636
1637    fn summary(&self, _: ()) -> Self::Summary {
1638        match self {
1639            ListItem::Unmeasured {
1640                size_hint,
1641                focus_handle,
1642            } => ListItemSummary {
1643                count: 1,
1644                rendered_count: 0,
1645                unrendered_count: 1,
1646                height: if let Some(size) = size_hint {
1647                    size.height
1648                } else {
1649                    px(0.)
1650                },
1651                has_focus_handles: focus_handle.is_some(),
1652                has_unknown_height: size_hint.is_none(),
1653            },
1654            ListItem::Measured {
1655                size, focus_handle, ..
1656            } => ListItemSummary {
1657                count: 1,
1658                rendered_count: 1,
1659                unrendered_count: 0,
1660                height: size.height,
1661                has_focus_handles: focus_handle.is_some(),
1662                has_unknown_height: false,
1663            },
1664        }
1665    }
1666}
1667
1668impl sum_tree::ContextLessSummary for ListItemSummary {
1669    fn zero() -> Self {
1670        Default::default()
1671    }
1672
1673    fn add_summary(&mut self, summary: &Self) {
1674        self.count += summary.count;
1675        self.rendered_count += summary.rendered_count;
1676        self.unrendered_count += summary.unrendered_count;
1677        self.height += summary.height;
1678        self.has_focus_handles |= summary.has_focus_handles;
1679        self.has_unknown_height |= summary.has_unknown_height;
1680    }
1681}
1682
1683impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1684    fn zero(_cx: ()) -> Self {
1685        Default::default()
1686    }
1687
1688    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1689        self.0 += summary.count;
1690    }
1691}
1692
1693impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1694    fn zero(_cx: ()) -> Self {
1695        Default::default()
1696    }
1697
1698    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1699        self.0 += summary.height;
1700    }
1701}
1702
1703impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1704    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1705        self.0.partial_cmp(&other.count).unwrap()
1706    }
1707}
1708
1709impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1710    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1711        self.0.partial_cmp(&other.height).unwrap()
1712    }
1713}
1714
1715#[cfg(test)]
1716mod test {
1717
1718    use gpui::{ScrollDelta, ScrollWheelEvent};
1719    use std::cell::{Cell, RefCell};
1720    use std::rc::Rc;
1721
1722    use crate::{
1723        self as gpui, AppContext, Bounds, Context, Element, FollowMode, IntoElement,
1724        ListSizingBehavior, ListState, ParentElement, Pixels, Render, Styled, TestAppContext,
1725        Window, canvas, div, list, point, px, size,
1726    };
1727
1728    #[gpui::test]
1729    fn test_horizontal_padding_insets_items(cx: &mut TestAppContext) {
1730        let cx = cx.add_empty_window();
1731
1732        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
1733        let item_bounds = Rc::new(RefCell::new(Vec::new()));
1734
1735        struct TestView {
1736            state: ListState,
1737            item_bounds: Rc<RefCell<Vec<Bounds<Pixels>>>>,
1738        }
1739        impl Render for TestView {
1740            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1741                let item_bounds = self.item_bounds.clone();
1742                list(self.state.clone(), move |_, _, _| {
1743                    let item_bounds = item_bounds.clone();
1744                    canvas(
1745                        move |bounds, _, _| item_bounds.borrow_mut().push(bounds),
1746                        |_, _, _, _| {},
1747                    )
1748                    .w_full()
1749                    .aspect_ratio(2.)
1750                    .into_any()
1751                })
1752                .pl(px(10.))
1753                .pr(px(30.))
1754                .w_full()
1755                .h_full()
1756            }
1757        }
1758
1759        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1760            cx.new(|_| TestView {
1761                state: state.clone(),
1762                item_bounds: item_bounds.clone(),
1763            })
1764            .into_any_element()
1765        });
1766
1767        for bounds in item_bounds.borrow().iter() {
1768            assert_eq!(bounds.origin.x, px(10.));
1769            assert_eq!(bounds.size.width, px(60.));
1770        }
1771        // Each item is 60px wide, so 30px tall: 300px in total.
1772        assert_eq!(state.max_offset_for_scrollbar().y, px(200.));
1773    }
1774
1775    #[gpui::test]
1776    fn test_inferred_width_includes_horizontal_padding(cx: &mut TestAppContext) {
1777        let cx = cx.add_empty_window();
1778
1779        let state = ListState::new(2, crate::ListAlignment::Top, px(10.));
1780        let full_width_item_bounds = Rc::new(RefCell::new(None));
1781
1782        struct TestView {
1783            state: ListState,
1784            full_width_item_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
1785        }
1786        impl Render for TestView {
1787            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1788                let full_width_item_bounds = self.full_width_item_bounds.clone();
1789                div().flex().size_full().child(
1790                    list(self.state.clone(), move |ix, _, _| {
1791                        if ix == 0 {
1792                            div().w(px(50.)).h(px(20.)).into_any()
1793                        } else {
1794                            let full_width_item_bounds = full_width_item_bounds.clone();
1795                            canvas(
1796                                move |bounds, _, _| {
1797                                    *full_width_item_bounds.borrow_mut() = Some(bounds)
1798                                },
1799                                |_, _, _, _| {},
1800                            )
1801                            .h(px(20.))
1802                            .w_full()
1803                            .into_any()
1804                        }
1805                    })
1806                    .with_sizing_behavior(ListSizingBehavior::Infer)
1807                    .pl(px(10.))
1808                    .pr(px(30.))
1809                    .h_full(),
1810                )
1811            }
1812        }
1813
1814        cx.draw(point(px(0.), px(0.)), size(px(200.), px(100.)), |_, cx| {
1815            cx.new(|_| TestView {
1816                state: state.clone(),
1817                full_width_item_bounds: full_width_item_bounds.clone(),
1818            })
1819            .into_any_element()
1820        });
1821
1822        let bounds = full_width_item_bounds
1823            .borrow()
1824            .expect("item 1 was not painted");
1825        assert_eq!(bounds.origin.x, px(10.));
1826        assert_eq!(bounds.size.width, px(50.));
1827    }
1828
1829    #[gpui::test]
1830    fn test_autoscroll_above_item_top_with_horizontal_padding(cx: &mut TestAppContext) {
1831        let cx = cx.add_empty_window();
1832
1833        let state = ListState::new(5, crate::ListAlignment::Top, px(0.));
1834        state.scroll_to(gpui::ListOffset {
1835            item_ix: 2,
1836            offset_in_item: px(0.),
1837        });
1838
1839        struct TestView(ListState);
1840        impl Render for TestView {
1841            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1842                list(self.0.clone(), |ix, _, _| {
1843                    if ix == 2 {
1844                        canvas(
1845                            |bounds, window, _| {
1846                                window.request_autoscroll(Bounds::from_corners(
1847                                    point(bounds.left(), bounds.top() - px(30.)),
1848                                    point(bounds.right(), bounds.top() + px(5.)),
1849                                ));
1850                            },
1851                            |_, _, _, _| {},
1852                        )
1853                        .w_full()
1854                        .aspect_ratio(2.)
1855                        .into_any()
1856                    } else {
1857                        div().w_full().aspect_ratio(2.).into_any()
1858                    }
1859                })
1860                .pl(px(10.))
1861                .pr(px(30.))
1862                .w_full()
1863                .h_full()
1864            }
1865        }
1866
1867        cx.draw(point(px(0.), px(0.)), size(px(100.), px(60.)), |_, cx| {
1868            cx.new(|_| TestView(state.clone())).into_any_element()
1869        });
1870
1871        // Items are 60px wide, so 30px tall: 30px above item 2 is the top of item 1.
1872        let scroll_top = state.logical_scroll_top();
1873        assert_eq!(scroll_top.item_ix, 1);
1874        assert_eq!(scroll_top.offset_in_item, px(0.));
1875    }
1876
1877    #[gpui::test]
1878    fn test_horizontal_padding_change_remeasures_items(cx: &mut TestAppContext) {
1879        let cx = cx.add_empty_window();
1880
1881        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
1882
1883        struct TestView {
1884            state: ListState,
1885            padding_right: Pixels,
1886        }
1887        impl Render for TestView {
1888            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1889                list(self.state.clone(), |_, _, _| {
1890                    div().w_full().aspect_ratio(2.).into_any()
1891                })
1892                .pl(px(10.))
1893                .pr(self.padding_right)
1894                .w_full()
1895                .h_full()
1896            }
1897        }
1898
1899        // The list width stays at 100px while the padding shrinks, so items go
1900        // from 60px wide (30px tall) to 80px wide (40px tall).
1901        for (padding_right, expected_max_offset) in [(px(30.), px(200.)), (px(10.), px(300.))] {
1902            cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1903                cx.new(|_| TestView {
1904                    state: state.clone(),
1905                    padding_right,
1906                })
1907                .into_any_element()
1908            });
1909            assert_eq!(state.max_offset_for_scrollbar().y, expected_max_offset);
1910        }
1911    }
1912
1913    #[gpui::test]
1914    fn test_border_and_padding_inset_items(cx: &mut TestAppContext) {
1915        let cx = cx.add_empty_window();
1916
1917        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
1918        let item_bounds = Rc::new(RefCell::new(Vec::new()));
1919
1920        struct TestView {
1921            state: ListState,
1922            item_bounds: Rc<RefCell<Vec<Bounds<Pixels>>>>,
1923        }
1924        impl Render for TestView {
1925            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1926                let item_bounds = self.item_bounds.clone();
1927                list(self.state.clone(), move |_, _, _| {
1928                    let item_bounds = item_bounds.clone();
1929                    canvas(
1930                        move |bounds, _, _| item_bounds.borrow_mut().push(bounds),
1931                        |_, _, _, _| {},
1932                    )
1933                    .w_full()
1934                    .aspect_ratio(2.)
1935                    .into_any()
1936                })
1937                .border_l_4()
1938                .pl(px(6.))
1939                .border_r_8()
1940                .pr(px(22.))
1941                .border_t_2()
1942                .pt(px(5.))
1943                .pb(px(3.))
1944                .w_full()
1945                .h_full()
1946            }
1947        }
1948
1949        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1950            cx.new(|_| TestView {
1951                state: state.clone(),
1952                item_bounds: item_bounds.clone(),
1953            })
1954            .into_any_element()
1955        });
1956
1957        let painted_bounds = item_bounds.borrow();
1958        assert!(!painted_bounds.is_empty());
1959        for bounds in painted_bounds.iter() {
1960            assert_eq!(bounds.origin.x, px(10.));
1961            assert_eq!(bounds.size.width, px(60.));
1962        }
1963        assert_eq!(state.max_offset_for_scrollbar().y, px(210.));
1964
1965        let reported_bounds = state.bounds_for_item(0).expect("item 0 should be measured");
1966        assert_eq!(reported_bounds, painted_bounds[0]);
1967        state.set_offset_from_scrollbar(point(px(0.), px(-210.)));
1968        assert_eq!(state.scroll_px_offset_for_scrollbar().y, px(-210.));
1969        assert_eq!(state.is_scrolled_to_end(), Some(true));
1970    }
1971
1972    #[gpui::test]
1973    fn test_autoscroll_above_item_top_renders_items_above(cx: &mut TestAppContext) {
1974        let cx = cx.add_empty_window();
1975
1976        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1977        state.scroll_to(gpui::ListOffset {
1978            item_ix: 2,
1979            offset_in_item: px(0.),
1980        });
1981
1982        struct TestView(ListState);
1983        impl Render for TestView {
1984            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1985                list(self.0.clone(), |ix, _, _| {
1986                    if ix == 2 {
1987                        // Request an autoscroll whose top sits 30px above item 2's
1988                        // own top, mimicking a scroll-margin overshoot.
1989                        canvas(
1990                            |bounds, window, _| {
1991                                window.request_autoscroll(Bounds::from_corners(
1992                                    point(bounds.left(), bounds.top() - px(30.)),
1993                                    point(bounds.right(), bounds.top() + px(5.)),
1994                                ));
1995                            },
1996                            |_, _, _, _| {},
1997                        )
1998                        .h(px(20.))
1999                        .w_full()
2000                        .into_any()
2001                    } else {
2002                        div().h(px(20.)).w_full().into_any()
2003                    }
2004                })
2005                .w_full()
2006                .h_full()
2007            }
2008        }
2009
2010        cx.draw(point(px(0.), px(0.)), size(px(100.), px(60.)), |_, cx| {
2011            cx.new(|_| TestView(state.clone())).into_any_element()
2012        });
2013
2014        // 30px above item 2's top, with 20px items, lands 10px into item 0.
2015        let scroll_top = state.logical_scroll_top();
2016        assert!(
2017            scroll_top.offset_in_item >= px(0.),
2018            "offset_in_item must never be negative (would leave blank space above), got {:?}",
2019            scroll_top.offset_in_item,
2020        );
2021        assert_eq!(scroll_top.item_ix, 0);
2022        assert_eq!(scroll_top.offset_in_item, px(10.));
2023    }
2024
2025    #[gpui::test]
2026    fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
2027        let cx = cx.add_empty_window();
2028
2029        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
2030
2031        // Ensure that the list is scrolled to the top
2032        state.scroll_to(gpui::ListOffset {
2033            item_ix: 0,
2034            offset_in_item: px(0.0),
2035        });
2036
2037        struct TestView(ListState);
2038        impl Render for TestView {
2039            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2040                list(self.0.clone(), |_, _, _| {
2041                    div().h(px(10.)).w_full().into_any()
2042                })
2043                .w_full()
2044                .h_full()
2045            }
2046        }
2047
2048        // Paint
2049        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2050            cx.new(|_| TestView(state.clone())).into_any_element()
2051        });
2052
2053        // Reset
2054        state.reset(5);
2055
2056        // And then receive a scroll event _before_ the next paint
2057        cx.simulate_event(ScrollWheelEvent {
2058            position: point(px(1.), px(1.)),
2059            delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
2060            ..Default::default()
2061        });
2062
2063        // Scroll position should stay at the top of the list
2064        assert_eq!(state.logical_scroll_top().item_ix, 0);
2065        assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
2066    }
2067
2068    #[gpui::test]
2069    fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
2070        let cx = cx.add_empty_window();
2071
2072        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
2073
2074        struct TestView(ListState);
2075        impl Render for TestView {
2076            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2077                list(self.0.clone(), |_, _, _| {
2078                    div().h(px(20.)).w_full().into_any()
2079                })
2080                .w_full()
2081                .h_full()
2082            }
2083        }
2084
2085        // Paint
2086        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
2087            cx.new(|_| TestView(state.clone())).into_any_element()
2088        });
2089
2090        // Test positive distance: start at item 1, move down 30px
2091        state.scroll_by(px(30.));
2092
2093        // Should move to item 2
2094        let offset = state.logical_scroll_top();
2095        assert_eq!(offset.item_ix, 1);
2096        assert_eq!(offset.offset_in_item, px(10.));
2097
2098        // Test negative distance: start at item 2, move up 30px
2099        state.scroll_by(px(-30.));
2100
2101        // Should move back to item 1
2102        let offset = state.logical_scroll_top();
2103        assert_eq!(offset.item_ix, 0);
2104        assert_eq!(offset.offset_in_item, px(0.));
2105
2106        // Test zero distance
2107        state.scroll_by(px(0.));
2108        let offset = state.logical_scroll_top();
2109        assert_eq!(offset.item_ix, 0);
2110        assert_eq!(offset.offset_in_item, px(0.));
2111    }
2112
2113    struct TestListView(ListState);
2114    impl Render for TestListView {
2115        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2116            list(self.0.clone(), |_, _, _| {
2117                div().h(px(20.)).w_full().into_any()
2118            })
2119            .w_full()
2120            .h_full()
2121        }
2122    }
2123
2124    #[gpui::test]
2125    fn test_item_viewport_queries_return_none_before_layout(_cx: &mut TestAppContext) {
2126        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2127
2128        assert_eq!(state.item_is_above_viewport(0), None);
2129        assert_eq!(state.item_is_below_viewport(0), None);
2130    }
2131
2132    #[gpui::test]
2133    fn test_item_viewport_queries_before_logical_scroll_top(cx: &mut TestAppContext) {
2134        let cx = cx.add_empty_window();
2135
2136        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2137
2138        state.scroll_to(gpui::ListOffset {
2139            item_ix: 2,
2140            offset_in_item: px(0.),
2141        });
2142        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2143            cx.new(|_| TestListView(state.clone())).into_any_element()
2144        });
2145
2146        assert_eq!(state.item_is_above_viewport(1), Some(true));
2147        assert_eq!(state.item_is_below_viewport(1), Some(false));
2148    }
2149
2150    #[gpui::test]
2151    fn test_item_viewport_queries_measured_item_inside_viewport(cx: &mut TestAppContext) {
2152        let cx = cx.add_empty_window();
2153
2154        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2155
2156        state.scroll_to(gpui::ListOffset {
2157            item_ix: 2,
2158            offset_in_item: px(0.),
2159        });
2160        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2161            cx.new(|_| TestListView(state.clone())).into_any_element()
2162        });
2163
2164        assert_eq!(state.item_is_above_viewport(2), Some(false));
2165        assert_eq!(state.item_is_below_viewport(2), Some(false));
2166    }
2167
2168    #[gpui::test]
2169    fn test_item_viewport_queries_measured_item_above_viewport(cx: &mut TestAppContext) {
2170        let cx = cx.add_empty_window();
2171
2172        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2173
2174        state.scroll_to(gpui::ListOffset {
2175            item_ix: 2,
2176            offset_in_item: px(20.),
2177        });
2178        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2179            cx.new(|_| TestListView(state.clone())).into_any_element()
2180        });
2181
2182        assert_eq!(state.item_is_above_viewport(2), Some(true));
2183        assert_eq!(state.item_is_below_viewport(2), Some(false));
2184    }
2185
2186    #[gpui::test]
2187    fn test_item_viewport_queries_measured_item_below_viewport(cx: &mut TestAppContext) {
2188        let cx = cx.add_empty_window();
2189
2190        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2191
2192        state.scroll_to(gpui::ListOffset {
2193            item_ix: 2,
2194            offset_in_item: px(0.),
2195        });
2196        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2197            cx.new(|_| TestListView(state.clone())).into_any_element()
2198        });
2199
2200        assert_eq!(state.item_is_above_viewport(3), Some(false));
2201        assert_eq!(state.item_is_below_viewport(3), Some(true));
2202    }
2203
2204    #[gpui::test]
2205    fn test_item_viewport_queries_remain_stable_with_zero_height_viewport(cx: &mut TestAppContext) {
2206        let cx = cx.add_empty_window();
2207
2208        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2209
2210        state.scroll_to(gpui::ListOffset {
2211            item_ix: 2,
2212            offset_in_item: px(0.),
2213        });
2214        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2215            cx.new(|_| TestListView(state.clone())).into_any_element()
2216        });
2217
2218        assert_eq!(state.item_is_above_viewport(3), Some(false));
2219        assert_eq!(state.item_is_below_viewport(3), Some(true));
2220
2221        // Squeeze the list to zero height, e.g. because a sibling element
2222        // (sized based on the queries above) consumed all the space. The
2223        // answers must remain definitive rather than becoming `None`,
2224        // otherwise the sibling's size can oscillate between frames.
2225        cx.draw(point(px(0.), px(0.)), size(px(100.), px(0.)), |_, cx| {
2226            cx.new(|_| TestListView(state.clone())).into_any_element()
2227        });
2228
2229        assert_eq!(state.item_is_above_viewport(1), Some(true));
2230        assert_eq!(state.item_is_below_viewport(1), Some(false));
2231        assert_eq!(state.item_is_above_viewport(3), Some(false));
2232        assert_eq!(state.item_is_below_viewport(3), Some(true));
2233    }
2234
2235    #[gpui::test]
2236    fn test_item_viewport_queries_after_scroll_to_end_before_layout(cx: &mut TestAppContext) {
2237        let cx = cx.add_empty_window();
2238
2239        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2240
2241        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2242            cx.new(|_| TestListView(state.clone())).into_any_element()
2243        });
2244
2245        state.scroll_to_end();
2246
2247        assert_eq!(state.logical_scroll_top().item_ix, state.item_count());
2248        assert_eq!(state.item_is_above_viewport(0), Some(true));
2249        assert_eq!(state.item_is_below_viewport(0), Some(false));
2250    }
2251
2252    #[gpui::test]
2253    fn test_measure_all_after_width_change(cx: &mut TestAppContext) {
2254        let cx = cx.add_empty_window();
2255
2256        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2257
2258        struct TestView(ListState);
2259        impl Render for TestView {
2260            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2261                list(self.0.clone(), |_, _, _| {
2262                    div().h(px(50.)).w_full().into_any()
2263                })
2264                .w_full()
2265                .h_full()
2266            }
2267        }
2268
2269        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2270
2271        // First draw at width 100: all 10 items measured (total 500px).
2272        // Viewport is 200px, so max scroll offset should be 300px.
2273        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2274            view.clone().into_any_element()
2275        });
2276        assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2277
2278        // Second draw at a different width: items get invalidated.
2279        // Without the fix, max_offset would drop because unmeasured items
2280        // contribute 0 height.
2281        cx.draw(point(px(0.), px(0.)), size(px(200.), px(200.)), |_, _| {
2282            view.into_any_element()
2283        });
2284        assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2285    }
2286
2287    #[gpui::test]
2288    fn test_remeasure(cx: &mut TestAppContext) {
2289        let cx = cx.add_empty_window();
2290
2291        // Create a list with 10 items, each 100px tall. We'll keep a reference
2292        // to the item height so we can later change the height and assert how
2293        // `ListState` handles it.
2294        let item_height = Rc::new(Cell::new(100usize));
2295        let state = ListState::new(10, crate::ListAlignment::Top, px(10.));
2296
2297        struct TestView {
2298            state: ListState,
2299            item_height: Rc<Cell<usize>>,
2300        }
2301
2302        impl Render for TestView {
2303            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2304                let height = self.item_height.get();
2305                list(self.state.clone(), move |_, _, _| {
2306                    div().h(px(height as f32)).w_full().into_any()
2307                })
2308                .w_full()
2309                .h_full()
2310            }
2311        }
2312
2313        let state_clone = state.clone();
2314        let item_height_clone = item_height.clone();
2315        let view = cx.update(|_, cx| {
2316            cx.new(|_| TestView {
2317                state: state_clone,
2318                item_height: item_height_clone,
2319            })
2320        });
2321
2322        // Simulate scrolling 40px inside the element with index 2. Since the
2323        // original item height is 100px, this equates to 40% inside the item.
2324        state.scroll_to(gpui::ListOffset {
2325            item_ix: 2,
2326            offset_in_item: px(40.),
2327        });
2328
2329        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2330            view.clone().into_any_element()
2331        });
2332
2333        let offset = state.logical_scroll_top();
2334        assert_eq!(offset.item_ix, 2);
2335        assert_eq!(offset.offset_in_item, px(40.));
2336
2337        // Update the `item_height` to be 50px instead of 100px so we can assert
2338        // that the scroll position is proportionally preserved, that is,
2339        // instead of 40px from the top of item 2, it should be 20px, since the
2340        // item's height has been halved.
2341        item_height.set(50);
2342        state.remeasure();
2343
2344        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2345            view.into_any_element()
2346        });
2347
2348        let offset = state.logical_scroll_top();
2349        assert_eq!(offset.item_ix, 2);
2350        assert_eq!(offset.offset_in_item, px(20.));
2351    }
2352
2353    #[gpui::test]
2354    fn test_remeasure_item_preserves_scroll_offset(cx: &mut TestAppContext) {
2355        let cx = cx.add_empty_window();
2356
2357        let item_height = Rc::new(Cell::new(100usize));
2358        let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2359
2360        struct TestView {
2361            state: ListState,
2362            item_height: Rc<Cell<usize>>,
2363        }
2364
2365        impl Render for TestView {
2366            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2367                let height = self.item_height.get();
2368                list(self.state.clone(), move |index, _, _| {
2369                    let height = if index == 5 { height } else { 100 };
2370                    div().h(px(height as f32)).w_full().into_any()
2371                })
2372                .w_full()
2373                .h_full()
2374            }
2375        }
2376
2377        let state_clone = state.clone();
2378        let item_height_clone = item_height.clone();
2379        let view = cx.update(|_, cx| {
2380            cx.new(|_| TestView {
2381                state: state_clone,
2382                item_height: item_height_clone,
2383            })
2384        });
2385
2386        state.scroll_to(gpui::ListOffset {
2387            item_ix: 5,
2388            offset_in_item: px(40.),
2389        });
2390
2391        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2392            view.clone().into_any_element()
2393        });
2394
2395        item_height.set(200);
2396        state.remeasure_items(5..6);
2397
2398        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2399            view.into_any_element()
2400        });
2401
2402        let offset = state.logical_scroll_top();
2403        assert_eq!(offset.item_ix, 5);
2404        assert_eq!(offset.offset_in_item, px(40.));
2405    }
2406
2407    #[gpui::test]
2408    fn test_remeasure_then_scroll_does_not_revert_scroll_position(cx: &mut TestAppContext) {
2409        let cx = cx.add_empty_window();
2410
2411        let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2412
2413        struct TestView(ListState);
2414        impl Render for TestView {
2415            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2416                list(self.0.clone(), |_, _, _| {
2417                    div().h(px(100.)).w_full().into_any()
2418                })
2419                .w_full()
2420                .h_full()
2421            }
2422        }
2423
2424        let view = {
2425            let state = state.clone();
2426            cx.update(|_, cx| cx.new(|_| TestView(state)))
2427        };
2428
2429        state.scroll_to(gpui::ListOffset {
2430            item_ix: 5,
2431            offset_in_item: px(40.),
2432        });
2433
2434        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2435            view.clone().into_any_element()
2436        });
2437
2438        state.remeasure_items(5..6);
2439
2440        cx.simulate_event(ScrollWheelEvent {
2441            position: point(px(50.), px(100.)),
2442            delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2443            ..Default::default()
2444        });
2445
2446        let offset = state.logical_scroll_top();
2447        assert_eq!(offset.item_ix, 5);
2448        assert_eq!(offset.offset_in_item, px(70.));
2449
2450        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2451            view.into_any_element()
2452        });
2453
2454        let offset = state.logical_scroll_top();
2455        assert_eq!(offset.item_ix, 5);
2456        assert_eq!(
2457            offset.offset_in_item,
2458            px(70.),
2459            "scrolling after a remeasure should not be reverted by the stale pending scroll"
2460        );
2461    }
2462
2463    #[gpui::test]
2464    fn test_scroll_after_remeasure_clamps_to_shrunk_item_height(cx: &mut TestAppContext) {
2465        let cx = cx.add_empty_window();
2466
2467        let item_height = Rc::new(Cell::new(100usize));
2468        let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2469
2470        struct TestView {
2471            state: ListState,
2472            item_height: Rc<Cell<usize>>,
2473        }
2474
2475        impl Render for TestView {
2476            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2477                let height = self.item_height.get();
2478                list(self.state.clone(), move |index, _, _| {
2479                    let height = if index == 5 { height } else { 100 };
2480                    div().h(px(height as f32)).w_full().into_any()
2481                })
2482                .w_full()
2483                .h_full()
2484            }
2485        }
2486
2487        let view = {
2488            let state = state.clone();
2489            let item_height = item_height.clone();
2490            cx.update(|_, cx| cx.new(|_| TestView { state, item_height }))
2491        };
2492
2493        state.scroll_to(gpui::ListOffset {
2494            item_ix: 5,
2495            offset_in_item: px(40.),
2496        });
2497
2498        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2499            view.clone().into_any_element()
2500        });
2501
2502        // Item 5 shrinks from 100px to 50px and is remeasured...
2503        item_height.set(50);
2504        state.remeasure_items(5..6);
2505
2506        // ...and then the user scrolls down by 30px before the next frame,
2507        // landing at offset 70.
2508        cx.simulate_event(ScrollWheelEvent {
2509            position: point(px(50.), px(100.)),
2510            delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2511            ..Default::default()
2512        });
2513
2514        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2515            view.into_any_element()
2516        });
2517
2518        // The rebased pending scroll clamps the user's offset to the item's
2519        // new height instead of leaving it pointing past the end of the item.
2520        let offset = state.logical_scroll_top();
2521        assert_eq!(offset.item_ix, 5);
2522        assert_eq!(offset.offset_in_item, px(50.));
2523    }
2524
2525    #[gpui::test]
2526    fn test_follow_tail_stays_at_bottom_as_items_grow(cx: &mut TestAppContext) {
2527        let cx = cx.add_empty_window();
2528
2529        // 10 items, each 50px tall → 500px total content, 200px viewport.
2530        // With follow-tail on, the list should always show the bottom.
2531        let item_height = Rc::new(Cell::new(50usize));
2532        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2533
2534        struct TestView {
2535            state: ListState,
2536            item_height: Rc<Cell<usize>>,
2537        }
2538        impl Render for TestView {
2539            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2540                let height = self.item_height.get();
2541                list(self.state.clone(), move |_, _, _| {
2542                    div().h(px(height as f32)).w_full().into_any()
2543                })
2544                .w_full()
2545                .h_full()
2546            }
2547        }
2548
2549        let state_clone = state.clone();
2550        let item_height_clone = item_height.clone();
2551        let view = cx.update(|_, cx| {
2552            cx.new(|_| TestView {
2553                state: state_clone,
2554                item_height: item_height_clone,
2555            })
2556        });
2557
2558        state.set_follow_mode(FollowMode::Tail);
2559
2560        // First paint — items are 50px, total 500px, viewport 200px.
2561        // Follow-tail should anchor to the end.
2562        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2563            view.clone().into_any_element()
2564        });
2565
2566        // The scroll should be at the bottom: the last visible items fill the
2567        // 200px viewport from the end of 500px of content (offset 300px).
2568        let offset = state.logical_scroll_top();
2569        assert_eq!(offset.item_ix, 6);
2570        assert_eq!(offset.offset_in_item, px(0.));
2571        assert!(state.is_following_tail());
2572
2573        // Simulate items growing (e.g. streaming content makes each item taller).
2574        // 10 items × 80px = 800px total.
2575        item_height.set(80);
2576        state.remeasure();
2577
2578        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2579            view.into_any_element()
2580        });
2581
2582        // After growth, follow-tail should have re-anchored to the new end.
2583        // 800px total − 200px viewport = 600px offset → item 7 at offset 40px,
2584        // but follow-tail anchors to item_count (10), and layout walks back to
2585        // fill 200px, landing at item 7 (7 × 80 = 560, 800 − 560 = 240 > 200,
2586        // so item 8: 8 × 80 = 640, 800 − 640 = 160 < 200 → keeps walking →
2587        // item 7: offset = 800 − 200 = 600, item_ix = 600/80 = 7, remainder 40).
2588        let offset = state.logical_scroll_top();
2589        assert_eq!(offset.item_ix, 7);
2590        assert_eq!(offset.offset_in_item, px(40.));
2591        assert!(state.is_following_tail());
2592    }
2593
2594    #[gpui::test]
2595    fn test_follow_tail_disengages_on_user_scroll(cx: &mut TestAppContext) {
2596        let cx = cx.add_empty_window();
2597
2598        // 10 items × 50px = 500px total, 200px viewport.
2599        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2600
2601        struct TestView(ListState);
2602        impl Render for TestView {
2603            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2604                list(self.0.clone(), |_, _, _| {
2605                    div().h(px(50.)).w_full().into_any()
2606                })
2607                .w_full()
2608                .h_full()
2609            }
2610        }
2611
2612        state.set_follow_mode(FollowMode::Tail);
2613
2614        // Paint with follow-tail — scroll anchored to the bottom.
2615        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, cx| {
2616            cx.new(|_| TestView(state.clone())).into_any_element()
2617        });
2618        assert!(state.is_following_tail());
2619
2620        // Simulate the user scrolling up.
2621        // This should disengage follow-tail.
2622        cx.simulate_event(ScrollWheelEvent {
2623            position: point(px(50.), px(100.)),
2624            delta: ScrollDelta::Pixels(point(px(0.), px(100.))),
2625            ..Default::default()
2626        });
2627
2628        assert!(
2629            !state.is_following_tail(),
2630            "follow-tail should disengage when the user scrolls toward the start"
2631        );
2632    }
2633
2634    #[gpui::test]
2635    fn test_follow_tail_disengages_on_scrollbar_reposition(cx: &mut TestAppContext) {
2636        let cx = cx.add_empty_window();
2637
2638        // 10 items × 50px = 500px total, 200px viewport.
2639        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2640
2641        struct TestView(ListState);
2642        impl Render for TestView {
2643            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2644                list(self.0.clone(), |_, _, _| {
2645                    div().h(px(50.)).w_full().into_any()
2646                })
2647                .w_full()
2648                .h_full()
2649            }
2650        }
2651
2652        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2653
2654        state.set_follow_mode(FollowMode::Tail);
2655
2656        // Paint with follow-tail — scroll anchored to the bottom.
2657        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2658            view.clone().into_any_element()
2659        });
2660        assert!(state.is_following_tail());
2661
2662        // Simulate the scrollbar moving the viewport to the middle.
2663        state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
2664
2665        let offset = state.logical_scroll_top();
2666        assert_eq!(offset.item_ix, 3);
2667        assert_eq!(offset.offset_in_item, px(0.));
2668        assert!(
2669            !state.is_following_tail(),
2670            "follow-tail should disengage when the scrollbar manually repositions the list"
2671        );
2672
2673        // A subsequent draw should preserve the user's manual position instead
2674        // of snapping back to the end.
2675        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2676            view.into_any_element()
2677        });
2678
2679        let offset = state.logical_scroll_top();
2680        assert_eq!(offset.item_ix, 3);
2681        assert_eq!(offset.offset_in_item, px(0.));
2682    }
2683
2684    #[gpui::test]
2685    fn test_scrollbar_drag_with_growing_content(cx: &mut TestAppContext) {
2686        let cx = cx.add_empty_window();
2687
2688        let last_item_height = Rc::new(Cell::new(50usize));
2689        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2690
2691        struct TestView {
2692            state: ListState,
2693            last_item_height: Rc<Cell<usize>>,
2694        }
2695        impl Render for TestView {
2696            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2697                let last_item_height = self.last_item_height.clone();
2698                list(self.state.clone(), move |index, _, _| {
2699                    let height = if index == 9 {
2700                        last_item_height.get()
2701                    } else {
2702                        50
2703                    };
2704                    div().h(px(height as f32)).w_full().into_any()
2705                })
2706                .w_full()
2707                .h_full()
2708            }
2709        }
2710
2711        let view = cx.update(|_, cx| {
2712            cx.new(|_| TestView {
2713                state: state.clone(),
2714                last_item_height: last_item_height.clone(),
2715            })
2716        });
2717
2718        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2719            view.clone().into_any_element()
2720        });
2721
2722        state.scrollbar_drag_started();
2723
2724        state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
2725        let scrollbar_offset_before_growth = state.scroll_px_offset_for_scrollbar();
2726
2727        let offset = state.logical_scroll_top();
2728        assert_eq!(offset.item_ix, 3);
2729        assert_eq!(offset.offset_in_item, px(0.));
2730
2731        last_item_height.set(550);
2732        state.remeasure_items(9..10);
2733        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2734            view.clone().into_any_element()
2735        });
2736
2737        assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2738        assert_eq!(
2739            state.scroll_px_offset_for_scrollbar(),
2740            scrollbar_offset_before_growth
2741        );
2742
2743        state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
2744        let offset = state.logical_scroll_top();
2745        assert_eq!(offset.item_ix, 3);
2746        assert_eq!(offset.offset_in_item, px(0.));
2747    }
2748
2749    #[gpui::test]
2750    fn test_set_follow_tail_snaps_to_bottom(cx: &mut TestAppContext) {
2751        let cx = cx.add_empty_window();
2752
2753        // 10 items × 50px = 500px total, 200px viewport.
2754        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2755
2756        struct TestView(ListState);
2757        impl Render for TestView {
2758            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2759                list(self.0.clone(), |_, _, _| {
2760                    div().h(px(50.)).w_full().into_any()
2761                })
2762                .w_full()
2763                .h_full()
2764            }
2765        }
2766
2767        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2768
2769        // Scroll to the middle of the list (item 3).
2770        state.scroll_to(gpui::ListOffset {
2771            item_ix: 3,
2772            offset_in_item: px(0.),
2773        });
2774
2775        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2776            view.clone().into_any_element()
2777        });
2778
2779        let offset = state.logical_scroll_top();
2780        assert_eq!(offset.item_ix, 3);
2781        assert_eq!(offset.offset_in_item, px(0.));
2782        assert!(!state.is_following_tail());
2783
2784        // Enable follow-tail — this should immediately snap the scroll anchor
2785        // to the end, like the user just sent a prompt.
2786        state.set_follow_mode(FollowMode::Tail);
2787
2788        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2789            view.into_any_element()
2790        });
2791
2792        // After paint, scroll should be at the bottom.
2793        // 500px total − 200px viewport = 300px offset → item 6, offset 0.
2794        let offset = state.logical_scroll_top();
2795        assert_eq!(offset.item_ix, 6);
2796        assert_eq!(offset.offset_in_item, px(0.));
2797        assert!(state.is_following_tail());
2798    }
2799
2800    #[gpui::test]
2801    fn test_bottom_aligned_scrollbar_offset_at_end(cx: &mut TestAppContext) {
2802        let cx = cx.add_empty_window();
2803
2804        const ITEMS: usize = 10;
2805        const ITEM_SIZE: f32 = 50.0;
2806
2807        let state = ListState::new(
2808            ITEMS,
2809            crate::ListAlignment::Bottom,
2810            px(ITEMS as f32 * ITEM_SIZE),
2811        );
2812
2813        struct TestView(ListState);
2814        impl Render for TestView {
2815            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2816                list(self.0.clone(), |_, _, _| {
2817                    div().h(px(ITEM_SIZE)).w_full().into_any()
2818                })
2819                .w_full()
2820                .h_full()
2821            }
2822        }
2823
2824        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
2825            cx.new(|_| TestView(state.clone())).into_any_element()
2826        });
2827
2828        // Bottom-aligned lists start pinned to the end: logical_scroll_top returns
2829        // item_ix == item_count, meaning no explicit scroll position has been set.
2830        assert_eq!(state.logical_scroll_top().item_ix, ITEMS);
2831
2832        let max_offset = state.max_offset_for_scrollbar();
2833        let scroll_offset = state.scroll_px_offset_for_scrollbar();
2834
2835        assert_eq!(
2836            -scroll_offset.y, max_offset.y,
2837            "scrollbar offset ({}) should equal max offset ({}) when list is pinned to bottom",
2838            -scroll_offset.y, max_offset.y,
2839        );
2840    }
2841
2842    /// When the user scrolls away from the bottom during follow_tail,
2843    /// follow_tail suspends. If they scroll back to the bottom, the
2844    /// next paint should re-engage follow_tail using fresh measurements.
2845    #[gpui::test]
2846    fn test_follow_tail_reengages_when_scrolled_back_to_bottom(cx: &mut TestAppContext) {
2847        let cx = cx.add_empty_window();
2848
2849        // 10 items × 50px = 500px total, 200px viewport.
2850        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2851
2852        struct TestView(ListState);
2853        impl Render for TestView {
2854            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2855                list(self.0.clone(), |_, _, _| {
2856                    div().h(px(50.)).w_full().into_any()
2857                })
2858                .w_full()
2859                .h_full()
2860            }
2861        }
2862
2863        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2864
2865        state.set_follow_mode(FollowMode::Tail);
2866
2867        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2868            view.clone().into_any_element()
2869        });
2870        assert!(state.is_following_tail());
2871
2872        // Scroll up — follow_tail should suspend (not fully disengage).
2873        cx.simulate_event(ScrollWheelEvent {
2874            position: point(px(50.), px(100.)),
2875            delta: ScrollDelta::Pixels(point(px(0.), px(50.))),
2876            ..Default::default()
2877        });
2878        assert!(!state.is_following_tail());
2879
2880        // Scroll back down to the bottom.
2881        cx.simulate_event(ScrollWheelEvent {
2882            position: point(px(50.), px(100.)),
2883            delta: ScrollDelta::Pixels(point(px(0.), px(-10000.))),
2884            ..Default::default()
2885        });
2886
2887        // After a paint, follow_tail should re-engage because the
2888        // layout confirmed we're at the true bottom.
2889        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2890            view.clone().into_any_element()
2891        });
2892        assert!(
2893            state.is_following_tail(),
2894            "follow_tail should re-engage after scrolling back to the bottom"
2895        );
2896    }
2897
2898    /// When an item is spliced to unmeasured (0px) while follow_tail
2899    /// is suspended, the re-engagement check should still work correctly
2900    #[gpui::test]
2901    fn test_follow_tail_reengagement_not_fooled_by_unmeasured_items(cx: &mut TestAppContext) {
2902        let cx = cx.add_empty_window();
2903
2904        // 20 items × 50px = 1000px total, 200px viewport, 1000px
2905        // overdraw so all items get measured during the follow_tail
2906        // paint (matching realistic production settings).
2907        let state = ListState::new(20, crate::ListAlignment::Top, px(1000.));
2908
2909        struct TestView(ListState);
2910        impl Render for TestView {
2911            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2912                list(self.0.clone(), |_, _, _| {
2913                    div().h(px(50.)).w_full().into_any()
2914                })
2915                .w_full()
2916                .h_full()
2917            }
2918        }
2919
2920        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2921
2922        state.set_follow_mode(FollowMode::Tail);
2923
2924        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2925            view.clone().into_any_element()
2926        });
2927        assert!(state.is_following_tail());
2928
2929        // Scroll up a meaningful amount — suspends follow_tail.
2930        // 20 items × 50px = 1000px. viewport 200px. scroll_max = 800px.
2931        // Scrolling up 200px puts us at 600px, clearly not at bottom.
2932        cx.simulate_event(ScrollWheelEvent {
2933            position: point(px(50.), px(100.)),
2934            delta: ScrollDelta::Pixels(point(px(0.), px(200.))),
2935            ..Default::default()
2936        });
2937        assert!(!state.is_following_tail());
2938
2939        // Invalidate the last item (simulates EntryUpdated calling
2940        // remeasure_items). This makes items.summary().height
2941        // temporarily wrong (0px for the invalidated item).
2942        state.remeasure_items(19..20);
2943
2944        // Paint — layout re-measures the invalidated item with its true
2945        // height. The re-engagement check uses these fresh measurements.
2946        // Since we scrolled 200px up from the 800px max, we're at
2947        // ~600px — NOT at the bottom, so follow_tail should NOT
2948        // re-engage.
2949        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2950            view.clone().into_any_element()
2951        });
2952        assert!(
2953            !state.is_following_tail(),
2954            "follow_tail should not falsely re-engage due to an unmeasured item \
2955             reducing items.summary().height"
2956        );
2957    }
2958
2959    #[gpui::test]
2960    fn test_follow_tail_reengages_after_scrollbar_disengagement(cx: &mut TestAppContext) {
2961        let cx = cx.add_empty_window();
2962
2963        // 10 items × 50px = 500px total, 200px viewport, scroll_max = 300px.
2964        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2965
2966        struct TestView(ListState);
2967        impl Render for TestView {
2968            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2969                list(self.0.clone(), |_, _, _| {
2970                    div().h(px(50.)).w_full().into_any()
2971                })
2972                .w_full()
2973                .h_full()
2974            }
2975        }
2976
2977        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2978
2979        state.set_follow_mode(FollowMode::Tail);
2980        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2981            view.clone().into_any_element()
2982        });
2983        assert!(state.is_following_tail());
2984
2985        // Drag the scrollbar up to the middle — follow_tail should suspend.
2986        state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
2987        assert!(!state.is_following_tail());
2988
2989        // Drag the scrollbar back to the bottom — follow_tail should re-engage
2990        // on the next paint.
2991        state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
2992        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2993            view.into_any_element()
2994        });
2995        assert!(
2996            state.is_following_tail(),
2997            "follow_tail should re-engage after scrolling back to the bottom via the scrollbar"
2998        );
2999    }
3000
3001    #[gpui::test]
3002    fn test_follow_tail_reengages_after_scrollbar_drag_to_bottom_while_growing(
3003        cx: &mut TestAppContext,
3004    ) {
3005        let cx = cx.add_empty_window();
3006
3007        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3008
3009        struct TestView(ListState);
3010        impl Render for TestView {
3011            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3012                list(self.0.clone(), |_, _, _| {
3013                    div().h(px(50.)).w_full().into_any()
3014                })
3015                .w_full()
3016                .h_full()
3017            }
3018        }
3019
3020        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3021
3022        state.set_follow_mode(FollowMode::Tail);
3023        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3024            view.clone().into_any_element()
3025        });
3026        assert!(state.is_following_tail());
3027
3028        state.scrollbar_drag_started();
3029
3030        state.splice(10..10, 10);
3031        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3032            view.clone().into_any_element()
3033        });
3034
3035        state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
3036        state.scrollbar_drag_ended();
3037
3038        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3039            view.into_any_element()
3040        });
3041
3042        assert!(
3043            state.is_following_tail(),
3044            "follow_tail should re-engage when the user drags the scrollbar to \
3045             the bottom of its track, even when content has grown during the drag \
3046             (so frozen_bottom < live_bottom)"
3047        );
3048    }
3049}