Skip to main content

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