Skip to main content

gpui/elements/
list.rs

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