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