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    Along as _, AnyElement, App, AvailableSpace, Axis, Bounds, ContentMask, DispatchPhase, Edges,
13    Element, EntityId, FocusHandle, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId,
14    IntoElement, Overflow, Pixels, Point, ScrollDelta, ScrollEvent, Size, Style, StyleRefinement,
15    Styled, 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) scroll_anchor: Option<ScrollAnchor>,
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    item_measurement_ready: Option<Box<dyn Fn(usize, &App) -> bool>>,
77    pub(crate) follow_state: FollowState,
78    pub(crate) version: crate::fast::dependencies::StateVersion,
79}
80
81#[derive(Clone, Copy)]
82pub(crate) struct ScrollAnchor {
83    pub(crate) position: ListOffset,
84    pub(crate) pending: Option<PendingScroll>,
85    pub(crate) provisional: bool,
86    pub(crate) pending_end: bool,
87}
88
89#[derive(Clone, Copy)]
90pub(crate) enum PendingScroll {
91    Absolute(Pixels),
92    Proportional(f32),
93}
94
95enum ScrollAnchorMode {
96    Absolute,
97    Proportional,
98}
99
100/// Controls whether the list automatically follows new content at the end.
101#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
102pub enum FollowMode {
103    /// Normal scrolling — no automatic following.
104    #[default]
105    Normal,
106    /// The list should auto-scroll along with the tail, when scrolled to bottom.
107    Tail,
108}
109
110#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
111pub(crate) enum FollowState {
112    #[default]
113    Normal,
114    Tail {
115        is_following: bool,
116    },
117}
118
119impl FollowState {
120    fn is_following(&self) -> bool {
121        matches!(self, FollowState::Tail { is_following: true })
122    }
123
124    fn has_stopped_following(&self) -> bool {
125        matches!(
126            self,
127            FollowState::Tail {
128                is_following: false
129            }
130        )
131    }
132
133    fn start_following(&mut self) {
134        if let FollowState::Tail {
135            is_following: false,
136        } = self
137        {
138            *self = FollowState::Tail { is_following: true };
139        }
140    }
141
142    fn stop_following(&mut self) {
143        if let FollowState::Tail { is_following: true } = self {
144            *self = FollowState::Tail {
145                is_following: false,
146            };
147        }
148    }
149}
150
151/// Whether the list is scrolling from top to bottom or bottom to top.
152#[derive(Clone, Copy, Debug, Eq, PartialEq)]
153pub enum ListAlignment {
154    /// The list is scrolling from top to bottom, like most lists.
155    Top,
156    /// The list is scrolling from bottom to top, like a chat log.
157    Bottom,
158}
159
160/// A scroll event that has been converted to be in terms of the list's items.
161pub struct ListScrollEvent {
162    /// The range of items currently visible in the list, after applying the scroll event.
163    pub visible_range: Range<usize>,
164
165    /// The number of items that are currently visible in the list, after applying the scroll event.
166    pub count: usize,
167
168    /// Whether the list has been scrolled.
169    pub is_scrolled: bool,
170
171    /// Whether the list is currently in follow-tail mode (auto-scrolling to end).
172    pub is_following_tail: bool,
173}
174
175/// The sizing behavior to apply during layout.
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
177pub enum ListSizingBehavior {
178    /// The list should calculate its size based on the size of its items.
179    Infer,
180    /// The list should not calculate a fixed size.
181    #[default]
182    Auto,
183}
184
185/// The measuring behavior to apply during layout.
186#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
187pub enum ListMeasuringBehavior {
188    /// Measure all items in the list.
189    /// Note: This can be expensive for the first frame in a large list.
190    Measure(bool),
191    /// Only measure visible items
192    #[default]
193    Visible,
194}
195
196impl ListMeasuringBehavior {
197    fn reset(&mut self) {
198        match self {
199            ListMeasuringBehavior::Measure(has_measured) => *has_measured = false,
200            ListMeasuringBehavior::Visible => {}
201        }
202    }
203}
204
205/// The horizontal sizing behavior to apply during layout.
206#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
207pub enum ListHorizontalSizingBehavior {
208    /// List items' width can never exceed the width of the list.
209    #[default]
210    FitList,
211    /// List items' width may go over the width of the list, if any item is wider.
212    Unconstrained,
213}
214
215struct LayoutItemsResponse {
216    max_item_width: Pixels,
217    scroll_top: ListOffset,
218    item_layouts: VecDeque<ItemLayout>,
219}
220
221struct ItemLayout {
222    index: usize,
223    element: AnyElement,
224    size: Size<Pixels>,
225}
226
227/// Frame state used by the [List] element after layout.
228pub struct ListPrepaintState {
229    hitbox: Hitbox,
230    layout: LayoutItemsResponse,
231}
232
233#[derive(Clone)]
234pub(crate) enum ListItem {
235    Unmeasured {
236        size_hint: Option<Size<Pixels>>,
237        focus_handle: Option<FocusHandle>,
238    },
239    Measured {
240        size: Size<Pixels>,
241        focus_handle: Option<FocusHandle>,
242    },
243}
244
245impl ListItem {
246    fn with_measurement(&self, size: Size<Pixels>, ready: bool) -> Self {
247        if ready {
248            Self::Measured {
249                size,
250                focus_handle: self.focus_handle(),
251            }
252        } else {
253            Self::Unmeasured {
254                size_hint: Some(size),
255                focus_handle: self.focus_handle(),
256            }
257        }
258    }
259
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 state = Self(Rc::new(RefCell::new(StateInner {
319            last_layout_bounds: None,
320            last_padding: None,
321            items: SumTree::default(),
322            scroll_anchor: None,
323            alignment,
324            overdraw,
325            scroll_handler: None,
326            reset: false,
327            scrollbar_drag_start_height: None,
328            measuring_behavior: ListMeasuringBehavior::default(),
329            item_measurement_ready: None,
330            follow_state: FollowState::default(),
331            version: crate::fast::dependencies::StateVersion::default(),
332        })));
333        state.splice(0..0, item_count);
334        state
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.set_scroll_anchor(None);
366            state.scrollbar_drag_start_height = None;
367            state.items.summary().count
368        };
369
370        self.splice(0..old_count, element_count);
371    }
372
373    /// Reset the list to `element_count` items, pre-populating every item with a
374    /// uniform height hint so the scrollbar thumb is correctly sized from the first
375    /// frame even for off-screen items.
376    pub fn reset_with_uniform_height(&self, element_count: usize, height: Pixels) {
377        self.reset(element_count);
378        self.apply_uniform_item_height(height);
379    }
380
381    fn apply_uniform_item_height(&self, height: Pixels) {
382        let size_hint = Size {
383            width: px(0.),
384            height,
385        };
386        let mut state = self.0.borrow_mut();
387        crate::fast::dependencies::StateVersion::bump(&state.version);
388        let new_items = state
389            .items
390            .iter()
391            .map(|item| ListItem::Unmeasured {
392                size_hint: Some(item.size_hint().unwrap_or(size_hint)),
393                focus_handle: item.focus_handle(),
394            })
395            .collect::<Vec<_>>();
396        let mut tree = SumTree::default();
397        tree.extend(new_items, ());
398        state.items = tree;
399    }
400
401    /// Remeasure all items while preserving proportional scroll position.
402    ///
403    /// Use this when item heights may have changed (e.g., font size changes)
404    /// but the number and identity of items remains the same.
405    pub fn remeasure(&self) {
406        let count = self.item_count();
407        self.remeasure_items_with_scroll_anchor(0..count, ScrollAnchorMode::Proportional);
408    }
409
410    /// Mark items in `range` as needing remeasurement while preserving
411    /// the current scroll position. Unlike [`Self::splice`], this does
412    /// not change the number of items or blow away `logical_scroll_top`.
413    ///
414    /// Use this when an item's content has changed and its rendered
415    /// height may be different (e.g., streaming text, tool results
416    /// loading), but the item itself still exists at the same index.
417    pub fn remeasure_items(&self, range: Range<usize>) {
418        self.remeasure_items_with_scroll_anchor(range, ScrollAnchorMode::Absolute);
419    }
420
421    fn remeasure_items_with_scroll_anchor(&self, range: Range<usize>, mode: ScrollAnchorMode) {
422        let state = &mut *self.0.borrow_mut();
423        crate::fast::dependencies::StateVersion::bump(&state.version);
424
425        if let Some(anchor) = state.scroll_anchor.as_mut()
426            && range.contains(&anchor.position.item_ix)
427        {
428            anchor.pending = match mode {
429                ScrollAnchorMode::Absolute => {
430                    Some(PendingScroll::Absolute(anchor.position.offset_in_item))
431                }
432                ScrollAnchorMode::Proportional => {
433                    let mut cursor = state.items.cursor::<Count>(());
434                    cursor.seek(&Count(anchor.position.item_ix), Bias::Right);
435                    cursor
436                        .item()
437                        .and_then(|item| item.size())
438                        .map(|size| {
439                            let fraction = if size.height > px(0.) {
440                                (anchor.position.offset_in_item / size.height).clamp(0., 1.)
441                            } else {
442                                0.
443                            };
444                            PendingScroll::Proportional(fraction)
445                        })
446                        .or(anchor.pending)
447                }
448            };
449        }
450
451        // Rebuild the tree, replacing items in the range with
452        // Unmeasured copies that keep their focus handles.
453        let new_items = {
454            let mut cursor = state.items.cursor::<Count>(());
455            let mut new_items = cursor.slice(&Count(range.start), Bias::Right);
456            let invalidated = cursor.slice(&Count(range.end), Bias::Right);
457            new_items.extend(
458                invalidated.iter().map(|item| ListItem::Unmeasured {
459                    size_hint: item.size_hint(),
460                    focus_handle: item.focus_handle(),
461                }),
462                (),
463            );
464            new_items.append(cursor.suffix(), ());
465            new_items
466        };
467        state.items = new_items;
468        state.measuring_behavior.reset();
469    }
470
471    /// The number of items in this list.
472    pub fn item_count(&self) -> usize {
473        self.0.borrow().items.summary().count
474    }
475
476    /// Whether the list is scrolled to the end, or `None` if the list is
477    /// not scrollable or the total content height is not yet known.
478    pub fn is_scrolled_to_end(&self) -> Option<bool> {
479        let state = self.0.borrow();
480        crate::fast::layers::lists::note_at_end_read(&state);
481        let bounds = state.last_layout_bounds?;
482        let summary = state.items.summary();
483        if summary.has_unknown_height {
484            return None;
485        }
486        let padding = state.last_padding.unwrap_or_default();
487        let content_height = summary.height + padding.top + padding.bottom;
488        let scroll_max = (content_height - bounds.size.height).max(px(0.));
489        if scroll_max <= px(0.) {
490            return None;
491        }
492        let scroll_top = state.scroll_top(&state.logical_scroll_top());
493        Some(scroll_top >= scroll_max)
494    }
495
496    /// Inform the list state that the items in `old_range` have been replaced
497    /// by `count` new items that must be recalculated.
498    pub fn splice(&self, old_range: Range<usize>, count: usize) {
499        self.splice_focusable(old_range, (0..count).map(|_| None))
500    }
501
502    /// Register with the list state that the items in `old_range` have been replaced
503    /// by new items. As opposed to [`Self::splice`], this method allows an iterator of optional focus handles
504    /// to be supplied to properly integrate with items in the list that can be focused. If a focused item
505    /// is scrolled out of view, the list will continue to render it to allow keyboard interaction.
506    pub fn splice_focusable(
507        &self,
508        old_range: Range<usize>,
509        focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
510    ) {
511        let state = &mut *self.0.borrow_mut();
512        crate::fast::dependencies::StateVersion::bump(&state.version);
513
514        let mut old_items = state.items.cursor::<Count>(());
515        let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right);
516        old_items.seek_forward(&Count(old_range.end), Bias::Right);
517
518        let mut spliced_count = 0;
519        new_items.extend(
520            focus_handles.into_iter().map(|focus_handle| {
521                spliced_count += 1;
522                ListItem::Unmeasured {
523                    size_hint: None,
524                    focus_handle,
525                }
526            }),
527            (),
528        );
529        new_items.append(old_items.suffix(), ());
530        drop(old_items);
531        state.items = new_items;
532
533        if let Some(anchor) = state.scroll_anchor.as_mut() {
534            if anchor.provisional && old_range.start <= anchor.position.item_ix {
535                anchor.provisional = false;
536                anchor.pending = None;
537            }
538            if old_range.contains(&anchor.position.item_ix) {
539                anchor.position = ListOffset {
540                    item_ix: old_range.start,
541                    offset_in_item: px(0.),
542                };
543                anchor.pending = None;
544            } else if old_range.end <= anchor.position.item_ix {
545                anchor.position.item_ix = anchor.position.item_ix - old_range.len() + spliced_count;
546            }
547        }
548    }
549
550    /// Set a handler that will be called when the list is scrolled.
551    pub fn set_scroll_handler(
552        &self,
553        handler: impl FnMut(&ListScrollEvent, &mut Window, &mut App) + 'static,
554    ) {
555        self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
556    }
557
558    /// Get the current scroll offset, in terms of the list's items.
559    pub fn logical_scroll_top(&self) -> ListOffset {
560        crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
561        self.0.borrow().logical_scroll_top()
562    }
563
564    /// Scroll the list by the given offset
565    pub fn scroll_by(&self, distance: Pixels) {
566        if distance == px(0.) {
567            return;
568        }
569
570        let current_offset = self.logical_scroll_top();
571        let state = &mut *self.0.borrow_mut();
572        crate::fast::dependencies::StateVersion::bump(&state.version);
573
574        if distance < px(0.) {
575            state.follow_state.stop_following();
576        }
577
578        let mut cursor = state.items.cursor::<ListItemSummary>(());
579        cursor.seek(&Count(current_offset.item_ix), Bias::Right);
580
581        let start_pixel_offset = cursor.start().height + current_offset.offset_in_item;
582        let new_pixel_offset = (start_pixel_offset + distance).max(px(0.));
583        if new_pixel_offset > start_pixel_offset {
584            cursor.seek_forward(&Height(new_pixel_offset), Bias::Right);
585        } else {
586            cursor.seek(&Height(new_pixel_offset), Bias::Right);
587        }
588
589        let scroll_top = ListOffset {
590            item_ix: cursor.start().count,
591            offset_in_item: new_pixel_offset - cursor.start().height,
592        };
593        drop(cursor);
594        state.set_scroll_anchor(Some(scroll_top));
595    }
596
597    /// Scroll the list to the very end (past the last item).
598    ///
599    /// Unlike [`scroll_to_reveal_item`], this uses the total item count as the
600    /// anchor, so the list's layout pass will walk backwards from the end and
601    /// always show the bottom of the last item — even when that item is still
602    /// growing (e.g. during streaming).
603    pub fn scroll_to_end(&self) {
604        let state = &mut *self.0.borrow_mut();
605        crate::fast::layers::lists::note_scrolled_to_end(state);
606        let item_count = state.items.summary().count;
607        state.set_scroll_anchor(Some(ListOffset {
608            item_ix: item_count,
609            offset_in_item: px(0.),
610        }));
611    }
612
613    /// Set the follow mode for the list. In `Tail` mode, the list
614    /// will auto-scroll to the end and re-engage after the user
615    /// scrolls back to the bottom. In `Normal` mode, no automatic
616    /// following occurs.
617    pub fn set_follow_mode(&self, mode: FollowMode) {
618        if mode == FollowMode::Normal {
619            self.pause_following_tail();
620        }
621        let state = &mut *self.0.borrow_mut();
622        crate::fast::dependencies::StateVersion::bump(&state.version);
623
624        match mode {
625            FollowMode::Normal => {
626                state.follow_state = FollowState::Normal;
627            }
628            FollowMode::Tail => {
629                state.follow_state = FollowState::Tail { is_following: true };
630                if matches!(mode, FollowMode::Tail) {
631                    let item_count = state.items.summary().count;
632                    state.set_scroll_anchor(Some(ListOffset {
633                        item_ix: item_count,
634                        offset_in_item: px(0.),
635                    }));
636                }
637            }
638        }
639    }
640
641    /// Pause tail-following, freezing the list at its current scroll
642    /// position. Unlike [`Self::set_follow_mode`] with [`FollowMode::Normal`],
643    /// this keeps the list in `Tail` mode, so it will resume following
644    /// automatically once the view returns to the bottom. No-op when the list
645    /// isn't currently following.
646    ///
647    /// Useful when something other than the user grows an item (e.g. zooming a
648    /// diagram) and the current position should stay put rather than snapping
649    /// to the end.
650    pub fn pause_following_tail(&self) {
651        crate::fast::dependencies::note_list_following_paused(&self.0.borrow());
652        let state = &mut *self.0.borrow_mut();
653        if state.follow_state.is_following()
654            && let Some(anchor) = state.scroll_anchor.as_mut()
655        {
656            anchor.pending_end = false;
657        }
658        state.follow_state.stop_following();
659    }
660
661    /// Sets a predicate queried after item layout to determine whether the measured height is stable.
662    /// Measurements reported as `false` remain provisional and are retried on later layouts.
663    /// The consumer must request a new frame when measurement becomes ready.
664    pub fn set_item_measurement_readiness(&self, ready: impl Fn(usize, &App) -> bool + 'static) {
665        self.0.borrow_mut().item_measurement_ready = Some(Box::new(ready));
666    }
667
668    /// Returns whether the list is currently actively following the
669    /// tail (snapping to the end on each layout).
670    pub fn is_following_tail(&self) -> bool {
671        matches!(
672            self.0.borrow().follow_state,
673            FollowState::Tail { is_following: true }
674        )
675    }
676
677    /// Scroll the list to the given offset
678    pub fn scroll_to(&self, mut scroll_top: ListOffset) {
679        let state = &mut *self.0.borrow_mut();
680        let scroll_start = crate::fast::dependencies::ListScrollStart::of(state);
681        let item_count = state.items.summary().count;
682        if scroll_top.item_ix >= item_count {
683            scroll_top.item_ix = item_count;
684            scroll_top.offset_in_item = px(0.);
685        }
686
687        if scroll_top.item_ix < item_count {
688            state.follow_state.stop_following();
689        }
690
691        crate::fast::dependencies::ListScrollStart::note_scrolled(scroll_start, state, &scroll_top);
692        state.set_scroll_anchor(Some(scroll_top));
693    }
694
695    /// Scroll the list to the given item, such that the item is fully visible.
696    pub fn scroll_to_reveal_item(&self, ix: usize) {
697        let state = &mut *self.0.borrow_mut();
698        crate::fast::dependencies::StateVersion::bump(&state.version);
699
700        let mut scroll_top = state.logical_scroll_top();
701        let height = state
702            .last_layout_bounds
703            .map_or(px(0.), |bounds| bounds.size.height);
704        let padding = state.last_padding.unwrap_or_default();
705
706        if ix <= scroll_top.item_ix {
707            scroll_top.item_ix = ix;
708            scroll_top.offset_in_item = px(0.);
709        } else {
710            let mut cursor = state.items.cursor::<ListItemSummary>(());
711            cursor.seek(&Count(ix + 1), Bias::Right);
712            let bottom = cursor.start().height + padding.top;
713            let goal_top = px(0.).max(bottom - height + padding.bottom);
714
715            cursor.seek(&Height(goal_top), Bias::Left);
716            let start_ix = cursor.start().count;
717            let start_item_top = cursor.start().height;
718
719            if start_ix >= scroll_top.item_ix {
720                scroll_top.item_ix = start_ix;
721                scroll_top.offset_in_item = goal_top - start_item_top;
722            }
723        }
724
725        state.set_scroll_anchor(Some(scroll_top));
726    }
727
728    /// Get the bounds for the given item in window coordinates, if it's
729    /// been rendered.
730    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
731        let state = &*self.0.borrow();
732        crate::fast::layers::invalidate::note_offset_read(&state.version);
733
734        let bounds = state.last_layout_bounds.unwrap_or_default();
735        let padding = state.last_padding.unwrap_or_default();
736        let scroll_top = state.logical_scroll_top();
737        if ix < scroll_top.item_ix {
738            return None;
739        }
740
741        let mut cursor = state.items.cursor::<Dimensions<Count, Height>>(());
742        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
743
744        let scroll_top = cursor.start().1.0 + scroll_top.offset_in_item;
745
746        cursor.seek_forward(&Count(ix), Bias::Right);
747        if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
748            let &Dimensions(Count(count), Height(top), _) = cursor.start();
749            if count == ix {
750                let top = bounds.top() + top - scroll_top;
751                return Some(Bounds::from_corners(
752                    point(bounds.left() + padding.left, top),
753                    point(bounds.right() - padding.right, top + size.height),
754                ));
755            }
756        }
757        None
758    }
759
760    /// Call this method when the user starts dragging the scrollbar.
761    ///
762    /// This will prevent the height reported to the scrollbar from changing during the drag
763    /// as items in the overdraw get measured, and help offset scroll position changes accordingly.
764    pub fn scrollbar_drag_started(&self) {
765        let mut state = self.0.borrow_mut();
766        crate::fast::dependencies::StateVersion::bump(&state.version);
767        state.scrollbar_drag_start_height = Some(state.items.summary().height);
768    }
769
770    /// Called when the user stops dragging the scrollbar.
771    ///
772    /// See `scrollbar_drag_started`.
773    pub fn scrollbar_drag_ended(&self) {
774        crate::fast::dependencies::StateVersion::bump(&self.0.borrow().version);
775        self.0.borrow_mut().scrollbar_drag_start_height.take();
776    }
777
778    /// Returns `true` if the scrollbar is currently being dragged.
779    ///
780    /// This is set between [`scrollbar_drag_started`](Self::scrollbar_drag_started)
781    /// and [`scrollbar_drag_ended`](Self::scrollbar_drag_ended) calls. Useful for
782    /// consumers that need to distinguish scrollbar drags from wheel/trackpad scrolls,
783    /// e.g. to suppress auto-scroll behavior during manual positioning.
784    pub fn is_scrollbar_dragging(&self) -> bool {
785        self.0.borrow().scrollbar_drag_start_height.is_some()
786    }
787
788    /// Set the offset from the scrollbar
789    pub fn set_offset_from_scrollbar(&self, point: Point<Pixels>) {
790        crate::fast::layers::invalidate::list_offset_set(&self.0.borrow().version);
791        self.0.borrow_mut().set_offset_from_scrollbar(point);
792    }
793
794    /// Returns the maximum scroll offset according to the items we have measured.
795    /// This value remains constant while dragging to prevent the scrollbar from moving away unexpectedly.
796    pub fn max_offset_for_scrollbar(&self) -> Point<Pixels> {
797        let state = self.0.borrow();
798        point(Pixels::ZERO, state.max_scroll_offset())
799    }
800
801    /// Returns the current scroll offset adjusted for the scrollbar.
802    ///
803    /// The returned offset has a negative `y` component representing
804    /// how far the content has scrolled.
805    pub fn scroll_px_offset_for_scrollbar(&self) -> Point<Pixels> {
806        let state = &self.0.borrow();
807        crate::fast::layers::invalidate::note_offset_read(&state.version);
808
809        if state.scroll_anchor.is_none() && state.alignment == ListAlignment::Bottom {
810            return Point::new(px(0.), -state.max_scroll_offset());
811        }
812
813        let logical_scroll_top = state.logical_scroll_top();
814
815        let mut cursor = state.items.cursor::<ListItemSummary>(());
816        let summary: ListItemSummary =
817            cursor.summary(&Count(logical_scroll_top.item_ix), Bias::Right);
818        let offset = summary.height + logical_scroll_top.offset_in_item;
819
820        Point::new(px(0.), -offset)
821    }
822
823    /// Return the bounds of the viewport in pixels.
824    pub fn viewport_bounds(&self) -> Bounds<Pixels> {
825        self.0.borrow().last_layout_bounds.unwrap_or_default()
826    }
827
828    /// Returns whether the item is entirely above the viewport, or `None` if
829    /// the list has not measured enough layout to know.
830    ///
831    /// A zero-height viewport still yields a definitive answer: callers may
832    /// size sibling UI based on this query (potentially squeezing the list
833    /// itself to zero height), so returning `None` in that case would make
834    /// the answer oscillate from frame to frame.
835    pub fn item_is_above_viewport(&self, ix: usize) -> Option<bool> {
836        let viewport_bounds = self.0.borrow().last_layout_bounds?;
837
838        let scroll_top = self.logical_scroll_top();
839        if ix < scroll_top.item_ix {
840            // Rows before the logical scroll top have no item bounds, but
841            // their position relative to the viewport is known from scroll state.
842            return Some(true);
843        }
844
845        let item_bounds = self.bounds_for_item(ix)?;
846        Some(item_bounds.bottom() <= viewport_bounds.top())
847    }
848
849    /// Returns whether the item is entirely below the viewport, or `None` if
850    /// the list has not measured enough layout to know.
851    ///
852    /// See [`Self::item_is_above_viewport`] for why a zero-height viewport
853    /// still yields a definitive answer.
854    pub fn item_is_below_viewport(&self, ix: usize) -> Option<bool> {
855        let viewport_bounds = self.0.borrow().last_layout_bounds?;
856
857        let scroll_top = self.logical_scroll_top();
858        if ix < scroll_top.item_ix {
859            // Rows before the logical scroll top have no item bounds, but
860            // their position relative to the viewport is known from scroll state.
861            return Some(false);
862        }
863
864        let item_bounds = self.bounds_for_item(ix)?;
865        Some(item_bounds.top() >= viewport_bounds.bottom())
866    }
867}
868
869impl StateInner {
870    fn max_scroll_offset(&self) -> Pixels {
871        let bounds = self.last_layout_bounds.unwrap_or_default();
872        let height = self
873            .scrollbar_drag_start_height
874            .unwrap_or_else(|| self.items.summary().height);
875        (height - bounds.size.height).max(px(0.))
876    }
877
878    fn visible_range(
879        items: &SumTree<ListItem>,
880        height: Pixels,
881        scroll_top: &ListOffset,
882    ) -> Range<usize> {
883        let mut cursor = items.cursor::<ListItemSummary>(());
884        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
885        let start_y = cursor.start().height + scroll_top.offset_in_item;
886        cursor.seek_forward(&Height(start_y + height), Bias::Left);
887        scroll_top.item_ix..cursor.start().count + 1
888    }
889
890    fn scroll(
891        &mut self,
892        scroll_top: &ListOffset,
893        height: Pixels,
894        delta: Point<Pixels>,
895        current_view: EntityId,
896        window: &mut Window,
897        cx: &mut App,
898    ) {
899        // Drop scroll events after a reset, since we can't calculate
900        // the new logical scroll top without the item heights
901        if self.reset || delta.y == px(0.) {
902            return;
903        }
904
905        let padding = self.last_padding.unwrap_or_default();
906        let scroll_max =
907            (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
908        let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
909            .max(px(0.))
910            .min(scroll_max);
911
912        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
913            self.set_scroll_anchor(None);
914        } else {
915            let (start, ..) =
916                self.items
917                    .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
918            let scroll_top = ListOffset {
919                item_ix: start.count,
920                offset_in_item: new_scroll_top - start.height,
921            };
922            self.set_scroll_anchor(Some(scroll_top));
923        }
924
925        if delta.y > px(0.) {
926            self.follow_state.stop_following();
927        }
928
929        if let Some(handler) = self.scroll_handler.as_mut() {
930            let visible_range = Self::visible_range(&self.items, height, scroll_top);
931            handler(
932                &ListScrollEvent {
933                    visible_range,
934                    count: self.items.summary().count,
935                    is_scrolled: self.scroll_anchor.is_some(),
936                    is_following_tail: matches!(
937                        self.follow_state,
938                        FollowState::Tail { is_following: true }
939                    ),
940                },
941                window,
942                cx,
943            );
944        }
945
946        crate::fast::layers::invalidate::note_list_scrolled(window, &self.version, current_view);
947        cx.notify(current_view);
948    }
949
950    pub(crate) fn logical_scroll_top(&self) -> ListOffset {
951        self.scroll_anchor
952            .map(|anchor| anchor.position)
953            .unwrap_or_else(|| match self.alignment {
954                ListAlignment::Top => ListOffset {
955                    item_ix: 0,
956                    offset_in_item: px(0.),
957                },
958                ListAlignment::Bottom => ListOffset {
959                    item_ix: self.items.summary().count,
960                    offset_in_item: px(0.),
961                },
962            })
963    }
964
965    pub(crate) fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
966        let (start, ..) = self.items.find::<ListItemSummary, _>(
967            (),
968            &Count(logical_scroll_top.item_ix),
969            Bias::Right,
970        );
971        start.height + logical_scroll_top.offset_in_item
972    }
973
974    fn is_item_ready(&self, index: usize, cx: &App) -> bool {
975        self.item_measurement_ready
976            .as_ref()
977            .is_none_or(|ready| ready(index, cx))
978    }
979
980    fn is_provisional(&self) -> bool {
981        self.scroll_anchor.is_some_and(|anchor| anchor.provisional)
982    }
983
984    fn set_scroll_anchor(&mut self, position: Option<ListOffset>) {
985        let Some(position) = position else {
986            self.scroll_anchor = None;
987            return;
988        };
989        let pending = self
990            .scroll_anchor
991            .and_then(|anchor| anchor.pending)
992            .filter(|_| position.item_ix < self.items.summary().count)
993            .and_then(|pending| match (pending, self.is_provisional()) {
994                (PendingScroll::Absolute(_), _) | (_, true) => {
995                    Some(PendingScroll::Absolute(position.offset_in_item))
996                }
997                (PendingScroll::Proportional(_), false) => {
998                    let mut cursor = self.items.cursor::<Count>(());
999                    cursor.seek(&Count(position.item_ix), Bias::Right);
1000                    cursor
1001                        .item()
1002                        .and_then(|item| item.size_hint())
1003                        .filter(|size| size.height > px(0.))
1004                        .map(|size| {
1005                            PendingScroll::Proportional(
1006                                (position.offset_in_item / size.height).clamp(0., 1.),
1007                            )
1008                        })
1009                }
1010            });
1011        self.scroll_anchor = Some(ScrollAnchor {
1012            position,
1013            pending,
1014            provisional: false,
1015            pending_end: false,
1016        });
1017    }
1018
1019    fn layout_all_items(
1020        &mut self,
1021        available_width: Pixels,
1022        render_item: &mut RenderItemFn,
1023        window: &mut Window,
1024        cx: &mut App,
1025    ) {
1026        match &mut self.measuring_behavior {
1027            ListMeasuringBehavior::Visible => {
1028                return;
1029            }
1030            ListMeasuringBehavior::Measure(has_measured) => {
1031                if *has_measured {
1032                    return;
1033                }
1034                *has_measured = true;
1035            }
1036        }
1037
1038        let cursor = self.items.cursor::<Count>(());
1039        let available_item_space = size(
1040            AvailableSpace::Definite(available_width),
1041            AvailableSpace::MinContent,
1042        );
1043
1044        let mut measured_items = Vec::default();
1045
1046        for (ix, item) in cursor.enumerate() {
1047            let size = item.size().unwrap_or_else(|| {
1048                let mut element = render_item(ix, window, cx);
1049                crate::fast::layout_key::layout_as_list_item(
1050                    &mut element,
1051                    ix,
1052                    available_item_space,
1053                    window,
1054                    cx,
1055                )
1056            });
1057
1058            measured_items.push(item.with_measurement(size, self.is_item_ready(ix, cx)));
1059        }
1060
1061        self.items = SumTree::from_iter(measured_items, ());
1062        self.measuring_behavior =
1063            ListMeasuringBehavior::Measure(self.items.summary().unrendered_count == 0);
1064    }
1065
1066    fn layout_items(
1067        &mut self,
1068        available_width: Option<Pixels>,
1069        available_height: Pixels,
1070        padding: &Edges<Pixels>,
1071        render_item: &mut RenderItemFn,
1072        window: &mut Window,
1073        cx: &mut App,
1074    ) -> LayoutItemsResponse {
1075        let old_items = self.items.clone();
1076        let mut measured_items = VecDeque::new();
1077        let mut item_layouts = VecDeque::new();
1078        let mut rendered_height = padding.top;
1079        let mut max_item_width = px(0.);
1080        let mut scroll_top = self.logical_scroll_top();
1081
1082        if self.follow_state.is_following()
1083            || self.scroll_anchor.is_some_and(|anchor| anchor.pending_end)
1084        {
1085            scroll_top = ListOffset {
1086                item_ix: self.items.summary().count,
1087                offset_in_item: px(0.),
1088            };
1089            self.set_scroll_anchor(Some(scroll_top));
1090        }
1091
1092        let preserve_anchor = scroll_top.item_ix < self.items.summary().count;
1093        if !preserve_anchor {
1094            self.follow_state.start_following();
1095        }
1096        let mut provisional = false;
1097        let mut rendered_focused_item = false;
1098
1099        let available_item_space = size(
1100            available_width.map_or(AvailableSpace::MaxContent, |width| {
1101                AvailableSpace::Definite(width)
1102            }),
1103            AvailableSpace::MinContent,
1104        );
1105
1106        let mut cursor = old_items.cursor::<Count>(());
1107
1108        // Render items after the scroll top, including those in the trailing overdraw
1109        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1110        for (ix, item) in cursor.by_ref().enumerate() {
1111            let visible_height = rendered_height - scroll_top.offset_in_item;
1112            if visible_height >= available_height + self.overdraw {
1113                break;
1114            }
1115
1116            let item_index = scroll_top.item_ix + ix;
1117            let (size, ready) = if (visible_height >= available_height
1118                || crate::fast::layers::lists::keeps_row(
1119                    window,
1120                    &self.version,
1121                    item_index,
1122                    item.size().is_some(),
1123                ))
1124                && let Some(size) = item.size()
1125            {
1126                (size, self.is_item_ready(item_index, cx))
1127            } else {
1128                let mut element = render_item(item_index, window, cx);
1129                let element_size = crate::fast::layout_key::layout_as_list_item(
1130                    &mut element,
1131                    item_index,
1132                    available_item_space,
1133                    window,
1134                    cx,
1135                );
1136                let ready = self.is_item_ready(item_index, cx);
1137                if ix == 0
1138                    && ready
1139                    && let Some(anchor) = self.scroll_anchor.as_mut()
1140                    && let Some(pending) = anchor.pending.take()
1141                {
1142                    scroll_top.offset_in_item = match pending {
1143                        PendingScroll::Absolute(offset) => offset.min(element_size.height),
1144                        PendingScroll::Proportional(fraction) => element_size.height * fraction,
1145                    };
1146                    anchor.position = scroll_top;
1147                }
1148
1149                if visible_height < available_height {
1150                    item_layouts.push_back(ItemLayout {
1151                        index: item_index,
1152                        element,
1153                        size: element_size,
1154                    });
1155                    if item.contains_focused(window, cx) {
1156                        rendered_focused_item = true;
1157                    }
1158                }
1159                (element_size, ready)
1160            };
1161
1162            rendered_height += size.height;
1163            max_item_width = max_item_width.max(size.width);
1164            provisional |= !ready;
1165            measured_items.push_back(item.with_measurement(size, ready));
1166            if !ready && visible_height >= available_height {
1167                break;
1168            }
1169        }
1170        rendered_height += padding.bottom;
1171
1172        // Prepare to start walking upward from the item at the scroll top.
1173        cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1174
1175        // If the rendered items do not fill the visible region, then adjust
1176        // the scroll top upward.
1177        if !provisional && rendered_height - scroll_top.offset_in_item < available_height {
1178            let forward_layout_count = item_layouts.len();
1179            let forward_focused = rendered_focused_item;
1180            while rendered_height < available_height {
1181                cursor.prev();
1182                if let Some(item) = cursor.item() {
1183                    let item_index = cursor.start().0;
1184                    let mut element = render_item(item_index, window, cx);
1185                    let element_size = crate::fast::layout_key::layout_as_list_item(
1186                        &mut element,
1187                        item_index,
1188                        available_item_space,
1189                        window,
1190                        cx,
1191                    );
1192                    let ready = self.is_item_ready(item_index, cx);
1193                    provisional |= !ready;
1194                    rendered_height += element_size.height;
1195                    measured_items.push_front(item.with_measurement(element_size, ready));
1196                    item_layouts.push_front(ItemLayout {
1197                        index: item_index,
1198                        element,
1199                        size: element_size,
1200                    });
1201                    if item.contains_focused(window, cx) {
1202                        rendered_focused_item = true;
1203                    }
1204                    if preserve_anchor && provisional {
1205                        break;
1206                    }
1207                } else {
1208                    break;
1209                }
1210            }
1211
1212            if preserve_anchor && provisional {
1213                item_layouts.drain(..item_layouts.len() - forward_layout_count);
1214                rendered_focused_item = forward_focused;
1215            } else {
1216                scroll_top = ListOffset {
1217                    item_ix: cursor.start().0,
1218                    offset_in_item: rendered_height - available_height,
1219                };
1220
1221                match self.alignment {
1222                    ListAlignment::Top => {
1223                        scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
1224                        self.set_scroll_anchor(Some(scroll_top));
1225                    }
1226                    ListAlignment::Bottom => {
1227                        scroll_top = ListOffset {
1228                            item_ix: cursor.start().0,
1229                            offset_in_item: rendered_height - available_height,
1230                        };
1231                        self.set_scroll_anchor(None);
1232                    }
1233                };
1234            }
1235        }
1236
1237        if let Some(anchor) = self.scroll_anchor.as_mut() {
1238            anchor.provisional = preserve_anchor && provisional;
1239            anchor.pending_end = !preserve_anchor && provisional;
1240        }
1241
1242        // Measure items in the leading overdraw
1243        if !provisional {
1244            let mut leading_overdraw = scroll_top.offset_in_item;
1245            while leading_overdraw < self.overdraw {
1246                cursor.prev();
1247                if let Some(item) = cursor.item() {
1248                    let size = if let ListItem::Measured { size, .. } = item {
1249                        *size
1250                    } else {
1251                        let mut element = render_item(cursor.start().0, window, cx);
1252                        crate::fast::layout_key::layout_as_list_item(
1253                            &mut element,
1254                            cursor.start().0,
1255                            available_item_space,
1256                            window,
1257                            cx,
1258                        )
1259                    };
1260
1261                    leading_overdraw += size.height;
1262                    let ready = self.is_item_ready(cursor.start().0, cx);
1263                    measured_items.push_front(item.with_measurement(size, ready));
1264                    if !ready {
1265                        break;
1266                    }
1267                } else {
1268                    break;
1269                }
1270            }
1271        }
1272
1273        let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
1274        let mut cursor = old_items.cursor::<Count>(());
1275        let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right);
1276        new_items.extend(measured_items, ());
1277        cursor.seek(&Count(measured_range.end), Bias::Right);
1278        new_items.append(cursor.suffix(), ());
1279        self.items = new_items;
1280
1281        // If follow_tail mode is on but the user scrolled away
1282        // (is_following is false), check whether the current scroll
1283        // position has returned to the bottom.
1284        if !provisional && self.follow_state.has_stopped_following() {
1285            let padding = self.last_padding.unwrap_or_default();
1286            let total_height = self.items.summary().height + padding.top + padding.bottom;
1287            let scroll_offset = self.scroll_top(&scroll_top);
1288            if scroll_offset + available_height >= total_height - px(1.0) {
1289                self.follow_state.start_following();
1290            }
1291        }
1292
1293        // If none of the visible items are focused, check if an off-screen item is focused
1294        // and include it to be rendered after the visible items so keyboard interaction continues
1295        // to work for it.
1296        if !rendered_focused_item {
1297            let mut cursor = self
1298                .items
1299                .filter::<_, Count>((), |summary| summary.has_focus_handles);
1300            cursor.next();
1301            while let Some(item) = cursor.item() {
1302                if item.contains_focused(window, cx) {
1303                    let item_index = cursor.start().0;
1304                    let mut element = render_item(cursor.start().0, window, cx);
1305                    let size = crate::fast::layout_key::layout_as_list_item(
1306                        &mut element,
1307                        item_index,
1308                        available_item_space,
1309                        window,
1310                        cx,
1311                    );
1312                    item_layouts.push_back(ItemLayout {
1313                        index: item_index,
1314                        element,
1315                        size,
1316                    });
1317                    break;
1318                }
1319                cursor.next();
1320            }
1321        }
1322
1323        LayoutItemsResponse {
1324            max_item_width,
1325            scroll_top,
1326            item_layouts,
1327        }
1328    }
1329
1330    fn prepaint_items(
1331        &mut self,
1332        bounds: Bounds<Pixels>,
1333        padding: Edges<Pixels>,
1334        autoscroll: bool,
1335        render_item: &mut RenderItemFn,
1336        window: &mut Window,
1337        cx: &mut App,
1338    ) -> Result<LayoutItemsResponse, ListOffset> {
1339        let item_width = bounds.size.width - padding.along(Axis::Horizontal);
1340        window.transact(|window| {
1341            match self.measuring_behavior {
1342                ListMeasuringBehavior::Measure(has_measured) if !has_measured => {
1343                    self.layout_all_items(item_width, render_item, window, cx);
1344                }
1345                _ => {}
1346            }
1347
1348            let mut layout_response = self.layout_items(
1349                Some(item_width),
1350                bounds.size.height,
1351                &padding,
1352                render_item,
1353                window,
1354                cx,
1355            );
1356
1357            // Avoid honoring autoscroll requests from elements other than our children.
1358            window.take_autoscroll();
1359
1360            // Only paint the visible items, if there is actually any space for them (taking padding into account)
1361            if bounds.size.height > padding.top + padding.bottom {
1362                let mut item_origin = bounds.origin + Point::new(padding.left, padding.top);
1363                crate::fast::layers::lists::snap_item_origin(
1364                    window,
1365                    self,
1366                    &layout_response.scroll_top,
1367                    &mut item_origin,
1368                );
1369                for item in &mut layout_response.item_layouts {
1370                    crate::fast::layers::lists::place_list_item(
1371                        window,
1372                        self,
1373                        item.index,
1374                        &mut item_origin,
1375                    );
1376                    window.with_content_mask(Some(ContentMask { bounds }), |window| {
1377                        item.element.prepaint_at(item_origin, window, cx);
1378                    });
1379
1380                    if let Some(autoscroll_bounds) = window.take_autoscroll()
1381                        && autoscroll
1382                    {
1383                        if autoscroll_bounds.top() < bounds.top() {
1384                            let mut item_ix = item.index;
1385                            let mut offset_in_item = autoscroll_bounds.top() - item_origin.y;
1386
1387                            // The requested top can sit above this item's own
1388                            // top. Walk into earlier items so the offset stays
1389                            // non-negative and no blank space appears above the
1390                            // list.
1391                            if offset_in_item < Pixels::ZERO {
1392                                let mut cursor = self.items.cursor::<Count>(());
1393                                cursor.seek(&Count(item_ix), Bias::Right);
1394                                while offset_in_item < Pixels::ZERO {
1395                                    cursor.prev();
1396                                    let Some(prev_item) = cursor.item() else {
1397                                        offset_in_item = Pixels::ZERO;
1398                                        break;
1399                                    };
1400                                    let size = prev_item.size().unwrap_or_else(|| {
1401                                        let mut element = render_item(cursor.start().0, window, cx);
1402                                        let item_available_size =
1403                                            size(item_width.into(), AvailableSpace::MinContent);
1404                                        crate::fast::layout_key::layout_as_list_item(
1405                                            &mut element,
1406                                            cursor.start().0,
1407                                            item_available_size,
1408                                            window,
1409                                            cx,
1410                                        )
1411                                    });
1412                                    item_ix = cursor.start().0;
1413                                    offset_in_item += size.height;
1414                                }
1415                            }
1416
1417                            return Err(ListOffset {
1418                                item_ix,
1419                                offset_in_item,
1420                            });
1421                        } else if autoscroll_bounds.bottom() > bounds.bottom() {
1422                            let mut cursor = self.items.cursor::<Count>(());
1423                            cursor.seek(&Count(item.index), Bias::Right);
1424                            let mut height = bounds.size.height - padding.top - padding.bottom;
1425
1426                            // Account for the height of the element down until the autoscroll bottom.
1427                            height -= autoscroll_bounds.bottom() - item_origin.y;
1428
1429                            // Keep decreasing the scroll top until we fill all the available space.
1430                            while height > Pixels::ZERO {
1431                                cursor.prev();
1432                                let Some(item) = cursor.item() else { break };
1433
1434                                let size = item.size().unwrap_or_else(|| {
1435                                    let mut item = render_item(cursor.start().0, window, cx);
1436                                    let item_available_size =
1437                                        size(item_width.into(), AvailableSpace::MinContent);
1438                                    crate::fast::layout_key::layout_as_list_item(
1439                                        &mut item,
1440                                        cursor.start().0,
1441                                        item_available_size,
1442                                        window,
1443                                        cx,
1444                                    )
1445                                });
1446                                height -= size.height;
1447                            }
1448
1449                            return Err(ListOffset {
1450                                item_ix: cursor.start().0,
1451                                offset_in_item: if height < Pixels::ZERO {
1452                                    -height
1453                                } else {
1454                                    Pixels::ZERO
1455                                },
1456                            });
1457                        }
1458                    }
1459
1460                    item_origin.y += item.size.height;
1461                }
1462            } else {
1463                layout_response.item_layouts.clear();
1464            }
1465
1466            Ok(layout_response)
1467        })
1468    }
1469
1470    // Scrollbar support
1471
1472    fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
1473        let Some(bounds) = self.last_layout_bounds else {
1474            return;
1475        };
1476        let height = bounds.size.height;
1477
1478        let padding = self.last_padding.unwrap_or_default();
1479        // Scrollbar drag positions are computed from the content height
1480        // captured at drag start, so map them back using the same height.
1481        let content_height = self
1482            .scrollbar_drag_start_height
1483            .unwrap_or_else(|| self.items.summary().height);
1484        let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
1485        let new_scroll_top = (-point.y).max(px(0.)).min(scroll_max);
1486
1487        // If content grew during the drag, the frozen bottom is below the
1488        // live bottom. Treat dragging to the frozen end as resuming tail follow.
1489        let dragged_to_end =
1490            scroll_max > px(0.) && new_scroll_top >= (scroll_max - px(1.0)).max(px(0.));
1491        if dragged_to_end && matches!(self.follow_state, FollowState::Tail { .. }) {
1492            self.follow_state = FollowState::Tail { is_following: true };
1493            let item_count = self.items.summary().count;
1494            self.set_scroll_anchor(Some(ListOffset {
1495                item_ix: item_count,
1496                offset_in_item: px(0.),
1497            }));
1498            return;
1499        }
1500
1501        self.follow_state.stop_following();
1502
1503        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
1504            self.set_scroll_anchor(None);
1505        } else {
1506            let (start, _, _) =
1507                self.items
1508                    .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
1509
1510            let scroll_top = ListOffset {
1511                item_ix: start.count,
1512                offset_in_item: new_scroll_top - start.height,
1513            };
1514            self.set_scroll_anchor(Some(scroll_top));
1515        }
1516    }
1517}
1518
1519impl std::fmt::Debug for ListItem {
1520    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1521        match self {
1522            Self::Unmeasured { .. } => write!(f, "Unrendered"),
1523            Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
1524        }
1525    }
1526}
1527
1528/// An offset into the list's items, in terms of the item index and the number
1529/// of pixels off the top left of the item.
1530#[derive(Debug, Clone, Copy, Default, PartialEq)]
1531pub struct ListOffset {
1532    /// The index of an item in the list
1533    pub item_ix: usize,
1534    /// The number of pixels to offset from the item index.
1535    pub offset_in_item: Pixels,
1536}
1537
1538impl Element for List {
1539    type RequestLayoutState = ();
1540    type PrepaintState = ListPrepaintState;
1541
1542    fn id(&self) -> Option<crate::ElementId> {
1543        None
1544    }
1545
1546    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1547        None
1548    }
1549
1550    fn request_layout(
1551        &mut self,
1552        _id: Option<&GlobalElementId>,
1553        _inspector_id: Option<&InspectorElementId>,
1554        window: &mut Window,
1555        cx: &mut App,
1556    ) -> (crate::LayoutId, Self::RequestLayoutState) {
1557        crate::fast::dependencies::note_state_read(cx, &self.state.0.borrow().version);
1558        let layout_id = match self.sizing_behavior {
1559            ListSizingBehavior::Infer => {
1560                let mut style = Style::default();
1561                style.overflow.y = Overflow::Scroll;
1562                style.refine(&self.style);
1563                window.with_text_style(style.text_style().cloned(), |window| {
1564                    let state = &mut *self.state.0.borrow_mut();
1565
1566                    let available_height = if let Some(last_bounds) = state.last_layout_bounds {
1567                        last_bounds.size.height
1568                    } else {
1569                        // If we don't have the last layout bounds (first render),
1570                        // we might just use the overdraw value as the available height to layout enough items.
1571                        state.overdraw
1572                    };
1573                    let padding = content_insets(
1574                        &style,
1575                        state.last_layout_bounds.unwrap_or_default().size,
1576                        window.rem_size(),
1577                    );
1578
1579                    let layout_response = state.layout_items(
1580                        None,
1581                        available_height,
1582                        &padding,
1583                        &mut self.render_item,
1584                        window,
1585                        cx,
1586                    );
1587                    let max_element_width = layout_response.max_item_width;
1588
1589                    let summary = state.items.summary();
1590                    let total_height = summary.height;
1591
1592                    window.request_measured_layout(
1593                        style,
1594                        move |known_dimensions, available_space, _window, _cx| {
1595                            let width =
1596                                known_dimensions
1597                                    .width
1598                                    .unwrap_or(match available_space.width {
1599                                        AvailableSpace::Definite(x) => x,
1600                                        AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1601                                            max_element_width
1602                                        }
1603                                    });
1604                            let height = match available_space.height {
1605                                AvailableSpace::Definite(height) => total_height.min(height),
1606                                AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1607                                    total_height
1608                                }
1609                            };
1610                            size(width, height)
1611                        },
1612                    )
1613                })
1614            }
1615            ListSizingBehavior::Auto => {
1616                let mut style = Style::default();
1617                style.refine(&self.style);
1618                window.with_text_style(style.text_style().cloned(), |window| {
1619                    window.request_layout(style, None, cx)
1620                })
1621            }
1622        };
1623        (layout_id, ())
1624    }
1625
1626    fn prepaint(
1627        &mut self,
1628        _id: Option<&GlobalElementId>,
1629        _inspector_id: Option<&InspectorElementId>,
1630        bounds: Bounds<Pixels>,
1631        _: &mut Self::RequestLayoutState,
1632        window: &mut Window,
1633        cx: &mut App,
1634    ) -> ListPrepaintState {
1635        let state = &mut *self.state.0.borrow_mut();
1636        state.reset = false;
1637
1638        let mut style = Style::default();
1639        style.refine(&self.style);
1640
1641        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1642
1643        let padding = content_insets(&style, bounds.size, window.rem_size());
1644
1645        // If the width of the list or the list content insets have changed,
1646        // invalidate all cached item heights
1647        let last_item_width =
1648            state
1649                .last_layout_bounds
1650                .zip(state.last_padding)
1651                .map(|(last_bounds, last_padding)| {
1652                    last_bounds.size.width - last_padding.along(Axis::Horizontal)
1653                });
1654        if last_item_width
1655            .is_none_or(|width| width != bounds.size.width - padding.along(Axis::Horizontal))
1656        {
1657            let new_items = SumTree::from_iter(
1658                state.items.iter().map(|item| ListItem::Unmeasured {
1659                    size_hint: None,
1660                    focus_handle: item.focus_handle(),
1661                }),
1662                (),
1663            );
1664
1665            state.items = new_items;
1666            state.measuring_behavior.reset();
1667        }
1668
1669        crate::fast::layers::lists::begin_list(window, cx, state, bounds);
1670        let mut autoscroll = true;
1671        let layout = loop {
1672            match state.prepaint_items(
1673                bounds,
1674                padding,
1675                autoscroll,
1676                &mut self.render_item,
1677                window,
1678                cx,
1679            ) {
1680                Ok(layout) => break layout,
1681                Err(autoscroll_request) => {
1682                    state.set_scroll_anchor(Some(autoscroll_request));
1683                    autoscroll = false;
1684                }
1685            }
1686        };
1687        crate::fast::layers::lists::end_list(
1688            window,
1689            cx,
1690            state,
1691            &mut self.render_item,
1692            bounds,
1693            padding,
1694        );
1695
1696        state.last_layout_bounds = Some(bounds);
1697        state.last_padding = Some(padding);
1698        ListPrepaintState { hitbox, layout }
1699    }
1700
1701    fn paint(
1702        &mut self,
1703        _id: Option<&GlobalElementId>,
1704        _inspector_id: Option<&InspectorElementId>,
1705        bounds: Bounds<crate::Pixels>,
1706        _: &mut Self::RequestLayoutState,
1707        prepaint: &mut Self::PrepaintState,
1708        window: &mut Window,
1709        cx: &mut App,
1710    ) {
1711        let current_view = window.current_view();
1712
1713        // Register the scroll listener before painting children so that, in
1714        // the bubble phase (which runs in reverse registration order),
1715        // children's scroll-wheel handlers run first and can stop propagation
1716        // to prevent the list from scrolling. This matches the ordering of
1717        // div-based scroll containers.
1718        let list_state = self.state.clone();
1719        let height = bounds.size.height;
1720        let scroll_top = prepaint.layout.scroll_top;
1721        let hitbox_id = prepaint.hitbox.id;
1722        let mut accumulated_scroll_delta = ScrollDelta::default();
1723        window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
1724            if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
1725                accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
1726                let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1727                list_state.0.borrow_mut().scroll(
1728                    &scroll_top,
1729                    height,
1730                    pixel_delta,
1731                    current_view,
1732                    window,
1733                    cx,
1734                )
1735            }
1736        });
1737
1738        window.with_content_mask(Some(ContentMask { bounds }), |window| {
1739            crate::fast::layers::lists::begin_paint_list(window, cx, &self.state);
1740            for item in &mut prepaint.layout.item_layouts {
1741                crate::fast::layers::lists::paint_row(
1742                    window,
1743                    cx,
1744                    Some(item.index),
1745                    |window, cx| item.element.paint(window, cx),
1746                );
1747            }
1748            crate::fast::layers::lists::end_paint_list(window, cx, &self.state);
1749        });
1750    }
1751}
1752
1753fn content_insets(style: &Style, size: Size<Pixels>, rem_size: Pixels) -> Edges<Pixels> {
1754    let padding = style.padding.to_pixels(size.into(), rem_size);
1755    let border = style.border_widths.to_pixels(rem_size);
1756
1757    padding + border
1758}
1759
1760impl IntoElement for List {
1761    type Element = Self;
1762
1763    fn into_element(self) -> Self::Element {
1764        self
1765    }
1766}
1767
1768impl Styled for List {
1769    fn style(&mut self) -> &mut StyleRefinement {
1770        &mut self.style
1771    }
1772}
1773
1774impl sum_tree::Item for ListItem {
1775    type Summary = ListItemSummary;
1776
1777    fn summary(&self, _: ()) -> Self::Summary {
1778        match self {
1779            ListItem::Unmeasured {
1780                size_hint,
1781                focus_handle,
1782            } => ListItemSummary {
1783                count: 1,
1784                rendered_count: 0,
1785                unrendered_count: 1,
1786                height: if let Some(size) = size_hint {
1787                    size.height
1788                } else {
1789                    px(0.)
1790                },
1791                has_focus_handles: focus_handle.is_some(),
1792                has_unknown_height: size_hint.is_none(),
1793            },
1794            ListItem::Measured {
1795                size, focus_handle, ..
1796            } => ListItemSummary {
1797                count: 1,
1798                rendered_count: 1,
1799                unrendered_count: 0,
1800                height: size.height,
1801                has_focus_handles: focus_handle.is_some(),
1802                has_unknown_height: false,
1803            },
1804        }
1805    }
1806}
1807
1808impl sum_tree::ContextLessSummary for ListItemSummary {
1809    fn zero() -> Self {
1810        Default::default()
1811    }
1812
1813    fn add_summary(&mut self, summary: &Self) {
1814        self.count += summary.count;
1815        self.rendered_count += summary.rendered_count;
1816        self.unrendered_count += summary.unrendered_count;
1817        self.height += summary.height;
1818        self.has_focus_handles |= summary.has_focus_handles;
1819        self.has_unknown_height |= summary.has_unknown_height;
1820    }
1821}
1822
1823impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1824    fn zero(_cx: ()) -> Self {
1825        Default::default()
1826    }
1827
1828    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1829        self.0 += summary.count;
1830    }
1831}
1832
1833impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1834    fn zero(_cx: ()) -> Self {
1835        Default::default()
1836    }
1837
1838    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1839        self.0 += summary.height;
1840    }
1841}
1842
1843impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1844    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1845        Ord::cmp(&self.0, &other.count)
1846    }
1847}
1848
1849impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1850    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1851        Ord::cmp(&self.0, &other.height)
1852    }
1853}
1854
1855#[cfg(test)]
1856mod test {
1857
1858    use gpui::{ScrollDelta, ScrollEvent};
1859    use std::cell::{Cell, RefCell};
1860    use std::rc::Rc;
1861
1862    use crate::{
1863        self as gpui, AnyElement, AppContext, Bounds, Context, Element, FollowMode,
1864        InteractiveElement, IntoElement, ListOffset, ListSizingBehavior, ListState, ParentElement,
1865        Pixels, Render, Styled, TestAppContext, VisualTestContext, Window, canvas, div, list,
1866        point, px, size,
1867    };
1868
1869    #[gpui::test]
1870    fn test_autoscroll_above_item_top_renders_items_above(cx: &mut TestAppContext) {
1871        let cx = cx.add_empty_window();
1872
1873        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1874        state.scroll_to(gpui::ListOffset {
1875            item_ix: 2,
1876            offset_in_item: px(0.),
1877        });
1878
1879        struct TestView(ListState);
1880        impl Render for TestView {
1881            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1882                list(self.0.clone(), |ix, _, _| {
1883                    if ix == 2 {
1884                        // Request an autoscroll whose top sits 30px above item 2's
1885                        // own top, mimicking a scroll-margin overshoot.
1886                        canvas(
1887                            |bounds, window, _| {
1888                                window.request_autoscroll(Bounds::from_corners(
1889                                    point(bounds.left(), bounds.top() - px(30.)),
1890                                    point(bounds.right(), bounds.top() + px(5.)),
1891                                ));
1892                            },
1893                            |_, _, _, _| {},
1894                        )
1895                        .h(px(20.))
1896                        .w_full()
1897                        .into_any()
1898                    } else {
1899                        div().h(px(20.)).w_full().into_any()
1900                    }
1901                })
1902                .w_full()
1903                .h_full()
1904            }
1905        }
1906
1907        cx.draw(point(px(0.), px(0.)), size(px(100.), px(60.)), |_, cx| {
1908            cx.new(|_| TestView(state.clone())).into_any_element()
1909        });
1910
1911        // 30px above item 2's top, with 20px items, lands 10px into item 0.
1912        let scroll_top = state.logical_scroll_top();
1913        assert!(
1914            scroll_top.offset_in_item >= px(0.),
1915            "offset_in_item must never be negative (would leave blank space above), got {:?}",
1916            scroll_top.offset_in_item,
1917        );
1918        assert_eq!(scroll_top.item_ix, 0);
1919        assert_eq!(scroll_top.offset_in_item, px(10.));
1920    }
1921
1922    #[gpui::test]
1923    fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
1924        let cx = cx.add_empty_window();
1925
1926        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1927
1928        // Ensure that the list is scrolled to the top
1929        state.scroll_to(gpui::ListOffset {
1930            item_ix: 0,
1931            offset_in_item: px(0.0),
1932        });
1933
1934        struct TestView(ListState);
1935        impl Render for TestView {
1936            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1937                list(self.0.clone(), |_, _, _| {
1938                    div().h(px(10.)).w_full().into_any()
1939                })
1940                .w_full()
1941                .h_full()
1942            }
1943        }
1944
1945        // Paint
1946        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1947            cx.new(|_| TestView(state.clone())).into_any_element()
1948        });
1949
1950        // Reset
1951        state.reset(5);
1952
1953        // And then receive a scroll event _before_ the next paint
1954        cx.simulate_event(ScrollEvent {
1955            position: point(px(1.), px(1.)),
1956            delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
1957            ..Default::default()
1958        });
1959
1960        // Scroll position should stay at the top of the list
1961        assert_eq!(state.logical_scroll_top().item_ix, 0);
1962        assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
1963    }
1964
1965    #[gpui::test]
1966    fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
1967        let cx = cx.add_empty_window();
1968
1969        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1970
1971        struct TestView(ListState);
1972        impl Render for TestView {
1973            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1974                list(self.0.clone(), |_, _, _| {
1975                    div().h(px(20.)).w_full().into_any()
1976                })
1977                .w_full()
1978                .h_full()
1979            }
1980        }
1981
1982        // Paint
1983        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1984            cx.new(|_| TestView(state.clone())).into_any_element()
1985        });
1986
1987        // Test positive distance: start at item 1, move down 30px
1988        state.scroll_by(px(30.));
1989
1990        // Should move to item 2
1991        let offset = state.logical_scroll_top();
1992        assert_eq!(offset.item_ix, 1);
1993        assert_eq!(offset.offset_in_item, px(10.));
1994
1995        // Test negative distance: start at item 2, move up 30px
1996        state.scroll_by(px(-30.));
1997
1998        // Should move back to item 1
1999        let offset = state.logical_scroll_top();
2000        assert_eq!(offset.item_ix, 0);
2001        assert_eq!(offset.offset_in_item, px(0.));
2002
2003        // Test zero distance
2004        state.scroll_by(px(0.));
2005        let offset = state.logical_scroll_top();
2006        assert_eq!(offset.item_ix, 0);
2007        assert_eq!(offset.offset_in_item, px(0.));
2008    }
2009
2010    #[gpui::test]
2011    fn test_child_scroll_handler_can_stop_list_scroll(cx: &mut TestAppContext) {
2012        let cx = cx.add_empty_window();
2013
2014        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
2015        let child_saw_event = Rc::new(Cell::new(false));
2016
2017        struct TestView {
2018            state: ListState,
2019            child_saw_event: Rc<Cell<bool>>,
2020        }
2021        impl Render for TestView {
2022            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2023                let child_saw_event = self.child_saw_event.clone();
2024                list(self.state.clone(), move |_, _, _| {
2025                    let child_saw_event = child_saw_event.clone();
2026                    div()
2027                        .h(px(20.))
2028                        .w_full()
2029                        .on_scroll(move |_, _, cx| {
2030                            child_saw_event.set(true);
2031                            cx.stop_propagation();
2032                        })
2033                        .into_any()
2034                })
2035                .w_full()
2036                .h_full()
2037            }
2038        }
2039
2040        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
2041            cx.new(|_| TestView {
2042                state: state.clone(),
2043                child_saw_event: child_saw_event.clone(),
2044            })
2045            .into_any_element()
2046        });
2047
2048        cx.simulate_event(ScrollEvent {
2049            position: point(px(50.), px(10.)),
2050            delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2051            ..Default::default()
2052        });
2053
2054        assert!(
2055            child_saw_event.get(),
2056            "the child's scroll-wheel handler should run"
2057        );
2058        // The child stopped propagation, so the list must not have scrolled.
2059        let offset = state.logical_scroll_top();
2060        assert_eq!(offset.item_ix, 0);
2061        assert_eq!(offset.offset_in_item, px(0.));
2062    }
2063
2064    #[gpui::test]
2065    fn test_item_viewport_queries_return_none_before_layout(_cx: &mut TestAppContext) {
2066        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2067
2068        assert_eq!(state.item_is_above_viewport(0), None);
2069        assert_eq!(state.item_is_below_viewport(0), None);
2070    }
2071
2072    #[gpui::test]
2073    fn test_item_viewport_queries_before_logical_scroll_top(cx: &mut TestAppContext) {
2074        let cx = cx.add_empty_window();
2075
2076        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2077
2078        state.scroll_to(gpui::ListOffset {
2079            item_ix: 2,
2080            offset_in_item: px(0.),
2081        });
2082        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2083            cx.new(|_| TestListView(state.clone())).into_any_element()
2084        });
2085
2086        assert_eq!(state.item_is_above_viewport(1), Some(true));
2087        assert_eq!(state.item_is_below_viewport(1), Some(false));
2088    }
2089
2090    #[gpui::test]
2091    fn test_item_viewport_queries_measured_item_inside_viewport(cx: &mut TestAppContext) {
2092        let cx = cx.add_empty_window();
2093
2094        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2095
2096        state.scroll_to(gpui::ListOffset {
2097            item_ix: 2,
2098            offset_in_item: px(0.),
2099        });
2100        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2101            cx.new(|_| TestListView(state.clone())).into_any_element()
2102        });
2103
2104        assert_eq!(state.item_is_above_viewport(2), Some(false));
2105        assert_eq!(state.item_is_below_viewport(2), Some(false));
2106    }
2107
2108    #[gpui::test]
2109    fn test_item_viewport_queries_measured_item_above_viewport(cx: &mut TestAppContext) {
2110        let cx = cx.add_empty_window();
2111
2112        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2113
2114        state.scroll_to(gpui::ListOffset {
2115            item_ix: 2,
2116            offset_in_item: px(20.),
2117        });
2118        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2119            cx.new(|_| TestListView(state.clone())).into_any_element()
2120        });
2121
2122        assert_eq!(state.item_is_above_viewport(2), Some(true));
2123        assert_eq!(state.item_is_below_viewport(2), Some(false));
2124    }
2125
2126    #[gpui::test]
2127    fn test_item_viewport_queries_measured_item_below_viewport(cx: &mut TestAppContext) {
2128        let cx = cx.add_empty_window();
2129
2130        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2131
2132        state.scroll_to(gpui::ListOffset {
2133            item_ix: 2,
2134            offset_in_item: px(0.),
2135        });
2136        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2137            cx.new(|_| TestListView(state.clone())).into_any_element()
2138        });
2139
2140        assert_eq!(state.item_is_above_viewport(3), Some(false));
2141        assert_eq!(state.item_is_below_viewport(3), Some(true));
2142    }
2143
2144    #[gpui::test]
2145    fn test_item_viewport_queries_remain_stable_with_zero_height_viewport(cx: &mut TestAppContext) {
2146        let cx = cx.add_empty_window();
2147
2148        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2149
2150        state.scroll_to(gpui::ListOffset {
2151            item_ix: 2,
2152            offset_in_item: px(0.),
2153        });
2154        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2155            cx.new(|_| TestListView(state.clone())).into_any_element()
2156        });
2157
2158        assert_eq!(state.item_is_above_viewport(3), Some(false));
2159        assert_eq!(state.item_is_below_viewport(3), Some(true));
2160
2161        // Squeeze the list to zero height, e.g. because a sibling element
2162        // (sized based on the queries above) consumed all the space. The
2163        // answers must remain definitive rather than becoming `None`,
2164        // otherwise the sibling's size can oscillate between frames.
2165        cx.draw(point(px(0.), px(0.)), size(px(100.), px(0.)), |_, cx| {
2166            cx.new(|_| TestListView(state.clone())).into_any_element()
2167        });
2168
2169        assert_eq!(state.item_is_above_viewport(1), Some(true));
2170        assert_eq!(state.item_is_below_viewport(1), Some(false));
2171        assert_eq!(state.item_is_above_viewport(3), Some(false));
2172        assert_eq!(state.item_is_below_viewport(3), Some(true));
2173    }
2174
2175    #[gpui::test]
2176    fn test_item_viewport_queries_after_scroll_to_end_before_layout(cx: &mut TestAppContext) {
2177        let cx = cx.add_empty_window();
2178
2179        let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2180
2181        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2182            cx.new(|_| TestListView(state.clone())).into_any_element()
2183        });
2184
2185        state.scroll_to_end();
2186
2187        assert_eq!(state.logical_scroll_top().item_ix, state.item_count());
2188        assert_eq!(state.item_is_above_viewport(0), Some(true));
2189        assert_eq!(state.item_is_below_viewport(0), Some(false));
2190    }
2191
2192    #[gpui::test]
2193    fn test_measure_all_after_width_change(cx: &mut TestAppContext) {
2194        let cx = cx.add_empty_window();
2195
2196        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2197
2198        struct TestView(ListState);
2199        impl Render for TestView {
2200            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2201                list(self.0.clone(), |_, _, _| {
2202                    div().h(px(50.)).w_full().into_any()
2203                })
2204                .w_full()
2205                .h_full()
2206            }
2207        }
2208
2209        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2210
2211        // First draw at width 100: all 10 items measured (total 500px).
2212        // Viewport is 200px, so max scroll offset should be 300px.
2213        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2214            view.clone().into_any_element()
2215        });
2216        assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2217
2218        // Second draw at a different width: items get invalidated.
2219        // Without the fix, max_offset would drop because unmeasured items
2220        // contribute 0 height.
2221        cx.draw(point(px(0.), px(0.)), size(px(200.), px(200.)), |_, _| {
2222            view.into_any_element()
2223        });
2224        assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2225    }
2226
2227    #[gpui::test]
2228    fn test_remeasure(cx: &mut TestAppContext) {
2229        let cx = cx.add_empty_window();
2230
2231        // Create a list with 10 items, each 100px tall. We'll keep a reference
2232        // to the item height so we can later change the height and assert how
2233        // `ListState` handles it.
2234        let item_height = Rc::new(Cell::new(100usize));
2235        let state = ListState::new(10, crate::ListAlignment::Top, px(10.));
2236
2237        struct TestView {
2238            state: ListState,
2239            item_height: Rc<Cell<usize>>,
2240        }
2241
2242        impl Render for TestView {
2243            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2244                let height = self.item_height.get();
2245                list(self.state.clone(), move |_, _, _| {
2246                    div().h(px(height as f32)).w_full().into_any()
2247                })
2248                .w_full()
2249                .h_full()
2250            }
2251        }
2252
2253        let state_clone = state.clone();
2254        let item_height_clone = item_height.clone();
2255        let view = cx.update(|_, cx| {
2256            cx.new(|_| TestView {
2257                state: state_clone,
2258                item_height: item_height_clone,
2259            })
2260        });
2261
2262        // Simulate scrolling 40px inside the element with index 2. Since the
2263        // original item height is 100px, this equates to 40% inside the item.
2264        state.scroll_to(gpui::ListOffset {
2265            item_ix: 2,
2266            offset_in_item: px(40.),
2267        });
2268
2269        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2270            view.clone().into_any_element()
2271        });
2272
2273        let offset = state.logical_scroll_top();
2274        assert_eq!(offset.item_ix, 2);
2275        assert_eq!(offset.offset_in_item, px(40.));
2276
2277        // Update the `item_height` to be 50px instead of 100px so we can assert
2278        // that the scroll position is proportionally preserved, that is,
2279        // instead of 40px from the top of item 2, it should be 20px, since the
2280        // item's height has been halved.
2281        item_height.set(50);
2282        state.remeasure();
2283
2284        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2285            view.into_any_element()
2286        });
2287
2288        let offset = state.logical_scroll_top();
2289        assert_eq!(offset.item_ix, 2);
2290        assert_eq!(offset.offset_in_item, px(20.));
2291    }
2292
2293    #[gpui::test]
2294    fn test_remeasure_item_preserves_scroll_offset(cx: &mut TestAppContext) {
2295        let cx = cx.add_empty_window();
2296
2297        let item_height = Rc::new(Cell::new(100usize));
2298        let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2299
2300        struct TestView {
2301            state: ListState,
2302            item_height: Rc<Cell<usize>>,
2303        }
2304
2305        impl Render for TestView {
2306            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2307                let height = self.item_height.get();
2308                list(self.state.clone(), move |index, _, _| {
2309                    let height = if index == 5 { height } else { 100 };
2310                    div().h(px(height as f32)).w_full().into_any()
2311                })
2312                .w_full()
2313                .h_full()
2314            }
2315        }
2316
2317        let state_clone = state.clone();
2318        let item_height_clone = item_height.clone();
2319        let view = cx.update(|_, cx| {
2320            cx.new(|_| TestView {
2321                state: state_clone,
2322                item_height: item_height_clone,
2323            })
2324        });
2325
2326        state.scroll_to(gpui::ListOffset {
2327            item_ix: 5,
2328            offset_in_item: px(40.),
2329        });
2330
2331        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2332            view.clone().into_any_element()
2333        });
2334
2335        item_height.set(200);
2336        state.remeasure_items(5..6);
2337
2338        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2339            view.into_any_element()
2340        });
2341
2342        let offset = state.logical_scroll_top();
2343        assert_eq!(offset.item_ix, 5);
2344        assert_eq!(offset.offset_in_item, px(40.));
2345    }
2346
2347    #[gpui::test]
2348    fn test_provisional_item_heights_keep_scroll_anchor(cx: &mut TestAppContext) {
2349        let cx = cx.add_empty_window();
2350        let state = ListState::new(20, crate::ListAlignment::Top, px(100.));
2351        let painted = Rc::new(RefCell::new(Vec::new()));
2352        let first_rendered = Rc::new(Cell::new(None::<usize>));
2353        let ready = item_readiness(&state, false);
2354        state.set_follow_mode(FollowMode::Tail);
2355        state.scroll_to(list_offset(10, 40.));
2356
2357        for (height, measurement_ready) in [(0., false), (100., false), (100., true)] {
2358            ready.set(measurement_ready);
2359            painted.borrow_mut().clear();
2360            first_rendered.set(None);
2361            draw_list(
2362                &state,
2363                200.,
2364                {
2365                    let painted = painted.clone();
2366                    let first_rendered = first_rendered.clone();
2367                    move |index| {
2368                        first_rendered.set(Some(first_rendered.get().unwrap_or(index).min(index)));
2369                        painted_item(index, height, &painted)
2370                    }
2371                },
2372                cx,
2373            );
2374            assert_eq!(state.logical_scroll_top(), list_offset(10, 40.));
2375            assert!(!state.is_following_tail());
2376            assert_eq!(
2377                first_rendered.get(),
2378                Some(if measurement_ready { 9 } else { 10 })
2379            );
2380            if height > 0. {
2381                assert_eq!(
2382                    painted.borrow().as_slice(),
2383                    &[
2384                        (10, px(-40.), px(60.)),
2385                        (11, px(60.), px(160.)),
2386                        (12, px(160.), px(260.)),
2387                    ]
2388                );
2389            }
2390        }
2391    }
2392
2393    #[gpui::test]
2394    fn test_unready_measurements_preserve_pending_fraction(cx: &mut TestAppContext) {
2395        let cx = cx.add_empty_window();
2396        for (provisional_height, destination, final_height, expected_offset) in [
2397            (Some(200.), None, 200., 100.),
2398            (None, Some(40.), 200., 80.),
2399            (Some(200.), Some(50.), 200., 50.),
2400            (Some(0.), Some(40.), 20., 20.),
2401            (Some(10.), Some(40.), 100., 40.),
2402            (Some(200.), Some(50.), 300., 50.),
2403        ] {
2404            let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2405            let painted = Rc::new(RefCell::new(Vec::new()));
2406            let draw = |height, cx: &mut VisualTestContext| {
2407                painted.borrow_mut().clear();
2408                let painted = painted.clone();
2409                draw_list(
2410                    &state,
2411                    200.,
2412                    move |index| {
2413                        painted_item(index, if index == 5 { height } else { 100. }, &painted)
2414                    },
2415                    cx,
2416                );
2417            };
2418            let ready = item_readiness(&state, true);
2419            state.scroll_to(list_offset(5, 50.));
2420            draw(100., cx);
2421            ready.set(false);
2422            state.remeasure();
2423            if let Some(height) = provisional_height {
2424                for height in [0., height, height] {
2425                    draw(height, cx);
2426                    assert_eq!(state.logical_scroll_top(), list_offset(5, 50.));
2427                }
2428            }
2429            if let Some(offset) = destination {
2430                state.scroll_to(list_offset(5, offset));
2431            }
2432            ready.set(true);
2433            for _ in 0..2 {
2434                draw(final_height, cx);
2435                assert_eq!(state.logical_scroll_top(), list_offset(5, expected_offset));
2436                assert_eq!(
2437                    painted.borrow().first().copied(),
2438                    Some((5, px(-expected_offset), px(final_height - expected_offset)))
2439                );
2440            }
2441        }
2442    }
2443
2444    #[gpui::test]
2445    fn test_navigation_cancels_provisional_and_paints_destination(cx: &mut TestAppContext) {
2446        let cx = cx.add_empty_window();
2447        for measured in [false, true] {
2448            let navigations: [(&str, fn(&ListState), usize, f32); 7] = [
2449                (
2450                    "scroll_to",
2451                    |state| state.scroll_to(list_offset(12, 0.)),
2452                    12,
2453                    0.,
2454                ),
2455                ("end", ListState::scroll_to_end, 19, 150.),
2456                ("down", |state| state.scroll_by(px(5000.)), 19, 150.),
2457                (
2458                    "up",
2459                    |state| state.scroll_by(px(-5000.)),
2460                    if measured { 0 } else { 6 },
2461                    0.,
2462                ),
2463                (
2464                    "reveal_below",
2465                    |state| state.scroll_to_reveal_item(10),
2466                    10,
2467                    150.,
2468                ),
2469                (
2470                    "reveal_above",
2471                    |state| state.scroll_to_reveal_item(0),
2472                    0,
2473                    0.,
2474                ),
2475                (
2476                    "follow_tail",
2477                    |state| state.set_follow_mode(FollowMode::Tail),
2478                    19,
2479                    150.,
2480                ),
2481            ];
2482            for (name, navigate, destination, top) in navigations {
2483                let state = ListState::new(20, crate::ListAlignment::Top, px(0.));
2484                let state = if measured { state.measure_all() } else { state };
2485                let painted = Rc::new(RefCell::new(Vec::new()));
2486                let draw = |cx: &mut VisualTestContext| {
2487                    painted.borrow_mut().clear();
2488                    let painted = painted.clone();
2489                    draw_list(
2490                        &state,
2491                        200.,
2492                        move |index| {
2493                            painted_item(index, if index == 5 { 0. } else { 50. }, &painted)
2494                        },
2495                        cx,
2496                    );
2497                };
2498                state.set_item_measurement_readiness(|index, _| index != 5);
2499                state.scroll_to(list_offset(5, 20.));
2500                state.remeasure_items(5..6);
2501                draw(cx);
2502                assert!(state.0.borrow().is_provisional(), "{name}");
2503                navigate(&state);
2504                assert!(!state.0.borrow().is_provisional(), "{name}");
2505                draw(cx);
2506                assert!(!state.0.borrow().is_provisional(), "{name}");
2507                assert_eq!(
2508                    painted
2509                        .borrow()
2510                        .iter()
2511                        .find(|(index, _, _)| *index == destination)
2512                        .copied(),
2513                    Some((destination, px(top), px(top + 50.))),
2514                    "{name}, measured={measured}",
2515                );
2516            }
2517        }
2518
2519        let navigations: [(&str, fn(&ListState)); 6] = [
2520            ("end_sentinel", |state| state.scroll_to(list_offset(3, 0.))),
2521            ("scroll_to_end", ListState::scroll_to_end),
2522            ("follow_tail", |state| {
2523                state.set_follow_mode(FollowMode::Tail)
2524            }),
2525            ("horizontal", ListState::scroll_to_end),
2526            ("pause_tail", |state| {
2527                state.set_follow_mode(FollowMode::Tail)
2528            }),
2529            ("disable_tail", |state| {
2530                state.set_follow_mode(FollowMode::Tail)
2531            }),
2532        ];
2533        for (name, navigate) in navigations {
2534            let state = ListState::new(3, crate::ListAlignment::Top, px(0.)).measure_all();
2535            let ready = item_readiness(&state, false);
2536            let painted = Rc::new(RefCell::new(Vec::new()));
2537            let draw = |height, cx: &mut VisualTestContext| {
2538                painted.borrow_mut().clear();
2539                let painted = painted.clone();
2540                draw_list(
2541                    &state,
2542                    200.,
2543                    move |index| painted_item(index, height, &painted),
2544                    cx,
2545                );
2546            };
2547            navigate(&state);
2548            for (height, measurement_ready, expected) in [
2549                (
2550                    100.,
2551                    false,
2552                    [(1, px(0.), px(100.)), (2, px(100.), px(200.))],
2553                ),
2554                (
2555                    150.,
2556                    true,
2557                    [(1, px(-100.), px(50.)), (2, px(50.), px(200.))],
2558                ),
2559            ] {
2560                if measurement_ready {
2561                    match name {
2562                        "horizontal" => cx.simulate_event(ScrollEvent {
2563                            position: point(px(50.), px(100.)),
2564                            delta: ScrollDelta::Pixels(point(px(20.), px(0.))),
2565                            ..ScrollEvent::default()
2566                        }),
2567                        "pause_tail" => state.pause_following_tail(),
2568                        "disable_tail" => state.set_follow_mode(FollowMode::Normal),
2569                        _ => {}
2570                    }
2571                }
2572                ready.set(measurement_ready);
2573                draw(height, cx);
2574                if !measurement_ready {
2575                    assert_eq!(
2576                        state.scroll_px_offset_for_scrollbar().y,
2577                        px(-100.),
2578                        "{name}"
2579                    );
2580                    assert_eq!(state.logical_scroll_top(), list_offset(1, 0.), "{name}");
2581                    assert_eq!(state.item_is_above_viewport(2), None, "{name}");
2582                }
2583                let paused = name == "pause_tail" || name == "disable_tail";
2584                let expected = if measurement_ready && paused {
2585                    [(1, px(0.), px(150.)), (2, px(150.), px(300.))]
2586                } else {
2587                    expected
2588                };
2589                assert_eq!(
2590                    state.is_following_tail(),
2591                    name == "follow_tail" || (paused && !measurement_ready),
2592                    "{name}"
2593                );
2594                assert_eq!(painted.borrow().as_slice(), &expected, "{name}");
2595            }
2596            ready.set(false);
2597            navigate(&state);
2598            draw(150., cx);
2599            state.scroll_by(px(-20.));
2600            draw(150., cx);
2601            assert_eq!(state.logical_scroll_top(), list_offset(1, 80.), "{name}");
2602            assert!(!state.is_following_tail(), "{name}");
2603            assert_eq!(
2604                painted.borrow().as_slice(),
2605                &[(1, px(-80.), px(70.)), (2, px(70.), px(220.)),],
2606                "{name}"
2607            );
2608        }
2609    }
2610
2611    #[gpui::test]
2612    fn test_unready_overdraw_and_backfill_preserve_scroll_anchor(cx: &mut TestAppContext) {
2613        let cx = cx.add_empty_window();
2614        for (overdraw, anchor, unready_item) in
2615            [(100., list_offset(0, 0.), 2), (0., list_offset(2, 40.), 1)]
2616        {
2617            let state = ListState::new(3, crate::ListAlignment::Top, px(overdraw));
2618            let ready = Rc::new(Cell::new(false));
2619            state.set_item_measurement_readiness({
2620                let ready = ready.clone();
2621                move |index, _| index != unready_item || ready.get()
2622            });
2623            let painted = Rc::new(RefCell::new(Vec::new()));
2624            let draw = |height, cx: &mut VisualTestContext| {
2625                painted.borrow_mut().clear();
2626                let painted = painted.clone();
2627                draw_list(
2628                    &state,
2629                    200.,
2630                    move |index| {
2631                        let height = if index == unready_item { height } else { 100. };
2632                        painted_item(index, height, &painted)
2633                    },
2634                    cx,
2635                );
2636            };
2637            state.set_follow_mode(FollowMode::Tail);
2638            state.scroll_to(anchor);
2639            draw(0., cx);
2640            assert_eq!(state.logical_scroll_top(), anchor);
2641            assert!(!state.is_following_tail());
2642            assert_eq!(
2643                *painted.borrow(),
2644                if unready_item == 2 {
2645                    vec![(0, px(0.), px(100.)), (1, px(100.), px(200.))]
2646                } else {
2647                    vec![(2, px(-40.), px(60.))]
2648                }
2649            );
2650            ready.set(true);
2651            draw(500., cx);
2652            if unready_item == 2 {
2653                assert_eq!(state.logical_scroll_top(), anchor);
2654                assert!(!state.is_following_tail());
2655                assert_eq!(state.max_offset_for_scrollbar().y, px(500.));
2656                assert_eq!(
2657                    painted.borrow().as_slice(),
2658                    &[(0, px(0.), px(100.)), (1, px(100.), px(200.))]
2659                );
2660            } else {
2661                assert_eq!(state.logical_scroll_top(), list_offset(1, 400.));
2662                assert!(state.is_following_tail());
2663                assert_eq!(
2664                    painted.borrow().as_slice(),
2665                    &[(1, px(-400.), px(100.)), (2, px(100.), px(200.))]
2666                );
2667            }
2668        }
2669    }
2670
2671    #[gpui::test]
2672    fn test_unready_overdraw_stops_at_first_pending_item(cx: &mut TestAppContext) {
2673        let cx = cx.add_empty_window();
2674        for anchor in [0, 10] {
2675            let state = ListState::new(13, crate::ListAlignment::Top, px(100.));
2676            let ready = Rc::new(Cell::new(false));
2677            let initially_ready = move |index| {
2678                if anchor == 0 { index < 2 } else { index >= 10 }
2679            };
2680            state.set_item_measurement_readiness({
2681                let ready = ready.clone();
2682                move |index, _| initially_ready(index) || ready.get()
2683            });
2684            state.scroll_to(list_offset(anchor, 0.));
2685            let rendered = Rc::new(RefCell::new(Vec::new()));
2686            let painted = Rc::new(RefCell::new(Vec::new()));
2687            let expected_frames = if anchor == 0 {
2688                [vec![0, 1, 2], vec![0, 1, 2], vec![0, 1, 2], vec![0, 1]]
2689            } else {
2690                [
2691                    vec![10, 11, 12, 9],
2692                    vec![10, 11, 9],
2693                    vec![10, 11, 9],
2694                    vec![10, 11],
2695                ]
2696            };
2697            for (frame, expected_rendered) in expected_frames.into_iter().enumerate() {
2698                let measurement_ready = frame >= 2;
2699                ready.set(measurement_ready);
2700                rendered.borrow_mut().clear();
2701                painted.borrow_mut().clear();
2702                draw_list(
2703                    &state,
2704                    200.,
2705                    {
2706                        let rendered = rendered.clone();
2707                        let painted = painted.clone();
2708                        move |index| {
2709                            rendered.borrow_mut().push(index);
2710                            let height = if initially_ready(index) || measurement_ready {
2711                                100.
2712                            } else {
2713                                0.
2714                            };
2715                            painted_item(index, height, &painted)
2716                        }
2717                    },
2718                    cx,
2719                );
2720                assert_eq!(*rendered.borrow(), expected_rendered);
2721                assert_eq!(state.item_count(), 13);
2722                assert_eq!(state.logical_scroll_top(), list_offset(anchor, 0.));
2723                assert_eq!(
2724                    painted.borrow().as_slice(),
2725                    &[(anchor, px(0.), px(100.)), (anchor + 1, px(100.), px(200.))]
2726                );
2727            }
2728        }
2729    }
2730
2731    #[gpui::test]
2732    fn test_scrollbar_and_reset_do_not_resurrect_provisional(cx: &mut TestAppContext) {
2733        let cx = cx.add_empty_window();
2734        let state = ListState::new(20, crate::ListAlignment::Top, px(0.));
2735        let painted = Rc::new(RefCell::new(Vec::new()));
2736        let draw = |cx: &mut VisualTestContext| {
2737            painted.borrow_mut().clear();
2738            let painted = painted.clone();
2739            draw_list(
2740                &state,
2741                200.,
2742                move |index| painted_item(index, if index == 5 { 0. } else { 50. }, &painted),
2743                cx,
2744            );
2745        };
2746        state.set_item_measurement_readiness(|index, _| index != 5);
2747        assert!(!state.0.borrow().is_provisional());
2748        state.set_follow_mode(FollowMode::Tail);
2749        for intervening_frame in [false, true] {
2750            state.scroll_to(list_offset(5, 20.));
2751            state.remeasure_items(5..6);
2752            draw(cx);
2753            state.scrollbar_drag_started();
2754            if intervening_frame {
2755                draw(cx);
2756                assert!(state.0.borrow().is_provisional());
2757            }
2758            state.set_offset_from_scrollbar(point(px(0.), px(-10_000.)));
2759            assert!(!state.0.borrow().is_provisional());
2760            state.scrollbar_drag_ended();
2761            assert!(!state.is_scrollbar_dragging());
2762            draw(cx);
2763            assert_eq!(
2764                painted.borrow().last().copied(),
2765                Some((19, px(150.), px(200.)))
2766            );
2767            assert!(!state.0.borrow().is_provisional());
2768            state.scroll_to(list_offset(5, 20.));
2769            assert!(!state.0.borrow().is_provisional());
2770            draw(cx);
2771            assert!(state.0.borrow().is_provisional());
2772            assert_eq!(state.logical_scroll_top(), list_offset(5, 20.));
2773        }
2774        state.remeasure_items(5..6);
2775        state.reset(20);
2776        assert!(!state.0.borrow().is_provisional());
2777        draw(cx);
2778        assert!(!state.0.borrow().is_provisional());
2779        assert_eq!(state.logical_scroll_top(), ListOffset::default());
2780        assert_eq!(
2781            painted.borrow().first().copied(),
2782            Some((0, px(0.), px(50.)))
2783        );
2784    }
2785
2786    #[gpui::test]
2787    fn test_splice_preserves_only_surviving_scroll_offsets(cx: &mut TestAppContext) {
2788        let cx = cx.add_empty_window();
2789        let painted = Rc::new(RefCell::new(Vec::new()));
2790        let draw = |state: &ListState, height, cx: &mut VisualTestContext| {
2791            painted.borrow_mut().clear();
2792            let painted = painted.clone();
2793            draw_list(
2794                state,
2795                200.,
2796                move |index| painted_item(index, height, &painted),
2797                cx,
2798            );
2799        };
2800        for (provisional, replacement_count) in [(true, 0), (false, 1)] {
2801            let state = ListState::new(20, crate::ListAlignment::Top, px(0.));
2802            let ready = item_readiness(&state, !provisional);
2803            state.scroll_to(list_offset(8, 50.));
2804            state.remeasure_items(8..9);
2805            if provisional {
2806                draw(&state, 100., cx);
2807            }
2808            state.splice(8..9, replacement_count);
2809            assert!(!state.0.borrow().is_provisional());
2810            ready.set(true);
2811            draw(&state, 100., cx);
2812            assert_eq!(state.logical_scroll_top(), list_offset(8, 0.));
2813            assert_eq!(
2814                painted.borrow().first().copied(),
2815                Some((8, px(0.), px(100.)))
2816            );
2817        }
2818        let state = ListState::new(20, crate::ListAlignment::Top, px(0.)).measure_all();
2819        state.scroll_to(list_offset(8, 50.));
2820        draw(&state, 100., cx);
2821        state.remeasure();
2822        state.splice(0..2, 0);
2823        draw(&state, 80., cx);
2824        assert_eq!(state.logical_scroll_top(), list_offset(6, 40.));
2825        assert_eq!(
2826            painted.borrow().first().copied(),
2827            Some((6, px(-40.), px(40.)))
2828        );
2829        let ready = item_readiness(&state, false);
2830        state.remeasure_items(6..7);
2831        state.splice(8..10, 3);
2832        draw(&state, 100., cx);
2833        assert!(state.0.borrow().is_provisional());
2834        assert_eq!(state.logical_scroll_top(), list_offset(6, 40.));
2835        state.splice(0..0, 2);
2836        assert!(!state.0.borrow().is_provisional());
2837        draw(&state, 100., cx);
2838        assert!(state.0.borrow().is_provisional());
2839        assert_eq!(state.logical_scroll_top(), list_offset(8, 40.));
2840        ready.set(true);
2841        draw(&state, 100., cx);
2842        assert_eq!(state.logical_scroll_top(), list_offset(8, 40.));
2843        assert_eq!(
2844            painted.borrow().first().copied(),
2845            Some((8, px(-40.), px(60.)))
2846        );
2847    }
2848
2849    #[gpui::test]
2850    fn test_child_autoscroll_overrides_pending_and_release_fills_viewport(cx: &mut TestAppContext) {
2851        let cx = cx.add_empty_window();
2852        for (count, child, request, expected, released) in [
2853            (10, 2, 40.0..45.0, list_offset(2, 40.), list_offset(2, 40.)),
2854            (3, 2, 40.0..45.0, list_offset(2, 40.), list_offset(1, 0.)),
2855            (10, 4, 80.0..90.0, list_offset(2, 90.), list_offset(2, 90.)),
2856            (10, 2, -130.0..5.0, list_offset(0, 70.), list_offset(0, 70.)),
2857            (10, 2, -250.0..5.0, list_offset(0, 0.), list_offset(0, 0.)),
2858        ] {
2859            let state = ListState::new(count, crate::ListAlignment::Top, px(0.));
2860            let requested = Rc::new(Cell::new(false));
2861            let painted = Rc::new(RefCell::new(Vec::new()));
2862            let draw = |cx: &mut VisualTestContext| {
2863                painted.borrow_mut().clear();
2864                let painted = painted.clone();
2865                let requested = requested.clone();
2866                let request = request.clone();
2867                draw_list(
2868                    &state,
2869                    200.,
2870                    move |index| {
2871                        let painted = painted.clone();
2872                        let requested = requested.clone();
2873                        let request = request.clone();
2874                        canvas(
2875                            move |bounds, window, _| {
2876                                if index == child && !requested.replace(true) {
2877                                    window.request_autoscroll(Bounds::from_corners(
2878                                        point(bounds.left(), bounds.top() + px(request.start)),
2879                                        point(bounds.right(), bounds.top() + px(request.end)),
2880                                    ));
2881                                }
2882                            },
2883                            move |bounds, _, _, _| {
2884                                painted
2885                                    .borrow_mut()
2886                                    .push((index, bounds.top(), bounds.bottom()));
2887                            },
2888                        )
2889                        .h(px(100.))
2890                        .w_full()
2891                        .into_any()
2892                    },
2893                    cx,
2894                );
2895            };
2896            let ready = item_readiness(&state, false);
2897            state.scroll_to(list_offset(2, 50.));
2898            state.remeasure_items(2..3);
2899            for _ in 0..2 {
2900                draw(cx);
2901                assert!(requested.get());
2902                assert!(state.0.borrow().is_provisional());
2903                assert_eq!(state.logical_scroll_top(), expected);
2904                assert_eq!(
2905                    painted.borrow().first().copied(),
2906                    Some((
2907                        expected.item_ix,
2908                        -expected.offset_in_item,
2909                        px(100.) - expected.offset_in_item,
2910                    ))
2911                );
2912            }
2913            ready.set(true);
2914            draw(cx);
2915            assert!(!state.0.borrow().is_provisional());
2916            assert_eq!(state.logical_scroll_top(), released);
2917            let visible_count = if released.offset_in_item == px(0.) {
2918                2
2919            } else {
2920                3
2921            };
2922            assert_eq!(
2923                painted.borrow().as_slice(),
2924                (0..visible_count)
2925                    .map(|index| {
2926                        let top = px(index as f32 * 100.) - released.offset_in_item;
2927                        (released.item_ix + index, top, top + px(100.))
2928                    })
2929                    .collect::<Vec<_>>()
2930                    .as_slice()
2931            );
2932        }
2933    }
2934
2935    #[gpui::test]
2936    fn test_remeasure_then_scroll_does_not_revert_scroll_position(cx: &mut TestAppContext) {
2937        let cx = cx.add_empty_window();
2938
2939        let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2940
2941        struct TestView(ListState);
2942        impl Render for TestView {
2943            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2944                list(self.0.clone(), |_, _, _| {
2945                    div().h(px(100.)).w_full().into_any()
2946                })
2947                .w_full()
2948                .h_full()
2949            }
2950        }
2951
2952        let view = {
2953            let state = state.clone();
2954            cx.update(|_, cx| cx.new(|_| TestView(state)))
2955        };
2956
2957        state.scroll_to(gpui::ListOffset {
2958            item_ix: 5,
2959            offset_in_item: px(40.),
2960        });
2961
2962        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2963            view.clone().into_any_element()
2964        });
2965
2966        state.remeasure_items(5..6);
2967
2968        cx.simulate_event(ScrollEvent {
2969            position: point(px(50.), px(100.)),
2970            delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2971            ..Default::default()
2972        });
2973
2974        let offset = state.logical_scroll_top();
2975        assert_eq!(offset.item_ix, 5);
2976        assert_eq!(offset.offset_in_item, px(70.));
2977
2978        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2979            view.into_any_element()
2980        });
2981
2982        let offset = state.logical_scroll_top();
2983        assert_eq!(offset.item_ix, 5);
2984        assert_eq!(
2985            offset.offset_in_item,
2986            px(70.),
2987            "scrolling after a remeasure should not be reverted by the stale pending scroll"
2988        );
2989    }
2990
2991    #[gpui::test]
2992    fn test_scroll_after_remeasure_clamps_to_shrunk_item_height(cx: &mut TestAppContext) {
2993        let cx = cx.add_empty_window();
2994        for provisional in [false, true] {
2995            let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2996            let painted = Rc::new(RefCell::new(Vec::new()));
2997            let draw = |height, cx: &mut VisualTestContext| {
2998                painted.borrow_mut().clear();
2999                let painted = painted.clone();
3000                draw_list(
3001                    &state,
3002                    200.,
3003                    move |index| {
3004                        painted_item(index, if index == 5 { height } else { 100. }, &painted)
3005                    },
3006                    cx,
3007                );
3008            };
3009            let ready = item_readiness(&state, true);
3010            state.scroll_to(list_offset(5, 40.));
3011            draw(100., cx);
3012            ready.set(!provisional);
3013            state.remeasure_items(5..6);
3014            if provisional {
3015                draw(100., cx);
3016            }
3017            ready.set(true);
3018            cx.simulate_event(ScrollEvent {
3019                position: point(px(50.), px(100.)),
3020                delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
3021                ..ScrollEvent::default()
3022            });
3023            assert_eq!(state.logical_scroll_top(), list_offset(5, 70.));
3024            for _ in 0..2 {
3025                draw(50., cx);
3026                assert_eq!(state.logical_scroll_top(), list_offset(5, 50.));
3027                assert_eq!(
3028                    painted
3029                        .borrow()
3030                        .iter()
3031                        .find(|(index, _, _)| *index == 6)
3032                        .copied(),
3033                    Some((6, px(0.), px(100.)))
3034                );
3035            }
3036        }
3037    }
3038
3039    #[gpui::test]
3040    fn test_follow_tail_stays_at_bottom_as_items_grow(cx: &mut TestAppContext) {
3041        let cx = cx.add_empty_window();
3042
3043        // 10 items, each 50px tall → 500px total content, 200px viewport.
3044        // With follow-tail on, the list should always show the bottom.
3045        let item_height = Rc::new(Cell::new(50usize));
3046        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3047
3048        struct TestView {
3049            state: ListState,
3050            item_height: Rc<Cell<usize>>,
3051        }
3052        impl Render for TestView {
3053            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3054                let height = self.item_height.get();
3055                list(self.state.clone(), move |_, _, _| {
3056                    div().h(px(height as f32)).w_full().into_any()
3057                })
3058                .w_full()
3059                .h_full()
3060            }
3061        }
3062
3063        let state_clone = state.clone();
3064        let item_height_clone = item_height.clone();
3065        let view = cx.update(|_, cx| {
3066            cx.new(|_| TestView {
3067                state: state_clone,
3068                item_height: item_height_clone,
3069            })
3070        });
3071
3072        state.set_follow_mode(FollowMode::Tail);
3073
3074        // First paint — items are 50px, total 500px, viewport 200px.
3075        // Follow-tail should anchor to the end.
3076        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3077            view.clone().into_any_element()
3078        });
3079
3080        // The scroll should be at the bottom: the last visible items fill the
3081        // 200px viewport from the end of 500px of content (offset 300px).
3082        let offset = state.logical_scroll_top();
3083        assert_eq!(offset.item_ix, 6);
3084        assert_eq!(offset.offset_in_item, px(0.));
3085        assert!(state.is_following_tail());
3086
3087        // Simulate items growing (e.g. streaming content makes each item taller).
3088        // 10 items × 80px = 800px total.
3089        item_height.set(80);
3090        state.remeasure();
3091
3092        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3093            view.into_any_element()
3094        });
3095
3096        // After growth, follow-tail should have re-anchored to the new end.
3097        // 800px total − 200px viewport = 600px offset → item 7 at offset 40px,
3098        // but follow-tail anchors to item_count (10), and layout walks back to
3099        // fill 200px, landing at item 7 (7 × 80 = 560, 800 − 560 = 240 > 200,
3100        // so item 8: 8 × 80 = 640, 800 − 640 = 160 < 200 → keeps walking →
3101        // item 7: offset = 800 − 200 = 600, item_ix = 600/80 = 7, remainder 40).
3102        let offset = state.logical_scroll_top();
3103        assert_eq!(offset.item_ix, 7);
3104        assert_eq!(offset.offset_in_item, px(40.));
3105        assert!(state.is_following_tail());
3106    }
3107
3108    #[gpui::test]
3109    fn test_pause_following_tail_reengages_when_still_at_bottom(cx: &mut TestAppContext) {
3110        let cx = cx.add_empty_window();
3111
3112        // 10 items × 50px = 500px total, 200px viewport.
3113        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3114
3115        struct TestView(ListState);
3116        impl Render for TestView {
3117            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3118                list(self.0.clone(), |_, _, _| {
3119                    div().h(px(50.)).w_full().into_any()
3120                })
3121                .w_full()
3122                .h_full()
3123            }
3124        }
3125
3126        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3127        state.set_follow_mode(FollowMode::Tail);
3128
3129        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3130            view.clone().into_any_element()
3131        });
3132        assert!(state.is_following_tail());
3133
3134        // Pausing while the view is still at the bottom (e.g. a no-op zoom)
3135        // must not strand follow-tail: the next layout has to re-engage so the
3136        // invariant "at the bottom + new content => visible" is preserved.
3137        state.pause_following_tail();
3138        assert!(!state.is_following_tail());
3139
3140        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3141            view.into_any_element()
3142        });
3143        assert!(
3144            state.is_following_tail(),
3145            "pausing while at the bottom must re-engage follow-tail on the next layout"
3146        );
3147    }
3148
3149    #[gpui::test]
3150    fn test_pause_following_tail_freezes_off_bottom(cx: &mut TestAppContext) {
3151        let cx = cx.add_empty_window();
3152
3153        // 10 items, 200px viewport. Item height is adjustable to simulate a
3154        // diagram block growing/shrinking on zoom.
3155        let item_height = Rc::new(Cell::new(50usize));
3156        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3157
3158        struct TestView {
3159            state: ListState,
3160            item_height: Rc<Cell<usize>>,
3161        }
3162        impl Render for TestView {
3163            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3164                let height = self.item_height.get();
3165                list(self.state.clone(), move |_, _, _| {
3166                    div().h(px(height as f32)).w_full().into_any()
3167                })
3168                .w_full()
3169                .h_full()
3170            }
3171        }
3172
3173        let view = cx.update(|_, cx| {
3174            cx.new(|_| TestView {
3175                state: state.clone(),
3176                item_height: item_height.clone(),
3177            })
3178        });
3179        state.set_follow_mode(FollowMode::Tail);
3180
3181        // At the bottom: 500px content, 200px viewport → top at item 6.
3182        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3183            view.clone().into_any_element()
3184        });
3185        assert_eq!(state.logical_scroll_top().item_ix, 6);
3186        assert!(state.is_following_tail());
3187
3188        // Pause, then grow items (a zoom-in that pushes content below the fold).
3189        // The frozen top must stay put rather than snapping to the new end, and
3190        // following stays paused since we're no longer at the bottom.
3191        state.pause_following_tail();
3192        item_height.set(80);
3193        state.remeasure();
3194        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3195            view.clone().into_any_element()
3196        });
3197        let offset = state.logical_scroll_top();
3198        assert_eq!(offset.item_ix, 6);
3199        assert_eq!(offset.offset_in_item, px(0.));
3200        assert!(
3201            !state.is_following_tail(),
3202            "a paused list must not re-engage while the frozen top is off the bottom"
3203        );
3204
3205        // Shrink back (zoom-out) so the frozen top once again reaches the
3206        // bottom: follow-tail must re-engage on its own.
3207        item_height.set(50);
3208        state.remeasure();
3209        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3210            view.into_any_element()
3211        });
3212        assert!(
3213            state.is_following_tail(),
3214            "returning to the bottom must restore follow-tail"
3215        );
3216    }
3217
3218    #[gpui::test]
3219    fn test_follow_tail_disengages_on_user_scroll(cx: &mut TestAppContext) {
3220        let cx = cx.add_empty_window();
3221
3222        // 10 items × 50px = 500px total, 200px viewport.
3223        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3224
3225        struct TestView(ListState);
3226        impl Render for TestView {
3227            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3228                list(self.0.clone(), |_, _, _| {
3229                    div().h(px(50.)).w_full().into_any()
3230                })
3231                .w_full()
3232                .h_full()
3233            }
3234        }
3235
3236        state.set_follow_mode(FollowMode::Tail);
3237
3238        // Paint with follow-tail — scroll anchored to the bottom.
3239        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, cx| {
3240            cx.new(|_| TestView(state.clone())).into_any_element()
3241        });
3242        assert!(state.is_following_tail());
3243
3244        // Simulate the user scrolling up.
3245        // This should disengage follow-tail.
3246        cx.simulate_event(ScrollEvent {
3247            position: point(px(50.), px(100.)),
3248            delta: ScrollDelta::Pixels(point(px(0.), px(100.))),
3249            ..Default::default()
3250        });
3251
3252        assert!(
3253            !state.is_following_tail(),
3254            "follow-tail should disengage when the user scrolls toward the start"
3255        );
3256    }
3257
3258    #[gpui::test]
3259    fn test_follow_tail_disengages_on_scrollbar_reposition(cx: &mut TestAppContext) {
3260        let cx = cx.add_empty_window();
3261
3262        // 10 items × 50px = 500px total, 200px viewport.
3263        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3264
3265        struct TestView(ListState);
3266        impl Render for TestView {
3267            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3268                list(self.0.clone(), |_, _, _| {
3269                    div().h(px(50.)).w_full().into_any()
3270                })
3271                .w_full()
3272                .h_full()
3273            }
3274        }
3275
3276        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3277
3278        state.set_follow_mode(FollowMode::Tail);
3279
3280        // Paint with follow-tail — scroll anchored to the bottom.
3281        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3282            view.clone().into_any_element()
3283        });
3284        assert!(state.is_following_tail());
3285
3286        // Simulate the scrollbar moving the viewport to the middle.
3287        state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3288
3289        let offset = state.logical_scroll_top();
3290        assert_eq!(offset.item_ix, 3);
3291        assert_eq!(offset.offset_in_item, px(0.));
3292        assert!(
3293            !state.is_following_tail(),
3294            "follow-tail should disengage when the scrollbar manually repositions the list"
3295        );
3296
3297        // A subsequent draw should preserve the user's manual position instead
3298        // of snapping back to the end.
3299        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3300            view.into_any_element()
3301        });
3302
3303        let offset = state.logical_scroll_top();
3304        assert_eq!(offset.item_ix, 3);
3305        assert_eq!(offset.offset_in_item, px(0.));
3306    }
3307
3308    #[gpui::test]
3309    fn test_scrollbar_drag_with_growing_content(cx: &mut TestAppContext) {
3310        let cx = cx.add_empty_window();
3311
3312        let last_item_height = Rc::new(Cell::new(50usize));
3313        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3314
3315        struct TestView {
3316            state: ListState,
3317            last_item_height: Rc<Cell<usize>>,
3318        }
3319        impl Render for TestView {
3320            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3321                let last_item_height = self.last_item_height.clone();
3322                list(self.state.clone(), move |index, _, _| {
3323                    let height = if index == 9 {
3324                        last_item_height.get()
3325                    } else {
3326                        50
3327                    };
3328                    div().h(px(height as f32)).w_full().into_any()
3329                })
3330                .w_full()
3331                .h_full()
3332            }
3333        }
3334
3335        let view = cx.update(|_, cx| {
3336            cx.new(|_| TestView {
3337                state: state.clone(),
3338                last_item_height: last_item_height.clone(),
3339            })
3340        });
3341
3342        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3343            view.clone().into_any_element()
3344        });
3345
3346        state.scrollbar_drag_started();
3347
3348        state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3349        let scrollbar_offset_before_growth = state.scroll_px_offset_for_scrollbar();
3350
3351        let offset = state.logical_scroll_top();
3352        assert_eq!(offset.item_ix, 3);
3353        assert_eq!(offset.offset_in_item, px(0.));
3354
3355        last_item_height.set(550);
3356        state.remeasure_items(9..10);
3357        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3358            view.clone().into_any_element()
3359        });
3360
3361        assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
3362        assert_eq!(
3363            state.scroll_px_offset_for_scrollbar(),
3364            scrollbar_offset_before_growth
3365        );
3366
3367        state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3368        let offset = state.logical_scroll_top();
3369        assert_eq!(offset.item_ix, 3);
3370        assert_eq!(offset.offset_in_item, px(0.));
3371    }
3372
3373    #[gpui::test]
3374    fn test_set_follow_tail_snaps_to_bottom(cx: &mut TestAppContext) {
3375        let cx = cx.add_empty_window();
3376
3377        // 10 items × 50px = 500px total, 200px viewport.
3378        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3379
3380        struct TestView(ListState);
3381        impl Render for TestView {
3382            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3383                list(self.0.clone(), |_, _, _| {
3384                    div().h(px(50.)).w_full().into_any()
3385                })
3386                .w_full()
3387                .h_full()
3388            }
3389        }
3390
3391        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3392
3393        // Scroll to the middle of the list (item 3).
3394        state.scroll_to(gpui::ListOffset {
3395            item_ix: 3,
3396            offset_in_item: px(0.),
3397        });
3398
3399        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3400            view.clone().into_any_element()
3401        });
3402
3403        let offset = state.logical_scroll_top();
3404        assert_eq!(offset.item_ix, 3);
3405        assert_eq!(offset.offset_in_item, px(0.));
3406        assert!(!state.is_following_tail());
3407
3408        // Enable follow-tail — this should immediately snap the scroll anchor
3409        // to the end, like the user just sent a prompt.
3410        state.set_follow_mode(FollowMode::Tail);
3411
3412        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3413            view.into_any_element()
3414        });
3415
3416        // After paint, scroll should be at the bottom.
3417        // 500px total − 200px viewport = 300px offset → item 6, offset 0.
3418        let offset = state.logical_scroll_top();
3419        assert_eq!(offset.item_ix, 6);
3420        assert_eq!(offset.offset_in_item, px(0.));
3421        assert!(state.is_following_tail());
3422    }
3423
3424    #[gpui::test]
3425    fn test_bottom_aligned_scrollbar_offset_at_end(cx: &mut TestAppContext) {
3426        let cx = cx.add_empty_window();
3427
3428        const ITEMS: usize = 10;
3429        const ITEM_SIZE: f32 = 50.0;
3430
3431        let state = ListState::new(
3432            ITEMS,
3433            crate::ListAlignment::Bottom,
3434            px(ITEMS as f32 * ITEM_SIZE),
3435        );
3436
3437        struct TestView(ListState);
3438        impl Render for TestView {
3439            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3440                list(self.0.clone(), |_, _, _| {
3441                    div().h(px(ITEM_SIZE)).w_full().into_any()
3442                })
3443                .w_full()
3444                .h_full()
3445            }
3446        }
3447
3448        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
3449            cx.new(|_| TestView(state.clone())).into_any_element()
3450        });
3451
3452        // Bottom-aligned lists start pinned to the end: logical_scroll_top returns
3453        // item_ix == item_count, meaning no explicit scroll position has been set.
3454        assert_eq!(state.logical_scroll_top().item_ix, ITEMS);
3455
3456        let max_offset = state.max_offset_for_scrollbar();
3457        let scroll_offset = state.scroll_px_offset_for_scrollbar();
3458
3459        assert_eq!(
3460            -scroll_offset.y, max_offset.y,
3461            "scrollbar offset ({}) should equal max offset ({}) when list is pinned to bottom",
3462            -scroll_offset.y, max_offset.y,
3463        );
3464    }
3465
3466    /// When the user scrolls away from the bottom during follow_tail,
3467    /// follow_tail suspends. If they scroll back to the bottom, the
3468    /// next paint should re-engage follow_tail using fresh measurements.
3469    #[gpui::test]
3470    fn test_follow_tail_reengages_when_scrolled_back_to_bottom(cx: &mut TestAppContext) {
3471        let cx = cx.add_empty_window();
3472
3473        // 10 items × 50px = 500px total, 200px viewport.
3474        let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3475
3476        struct TestView(ListState);
3477        impl Render for TestView {
3478            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3479                list(self.0.clone(), |_, _, _| {
3480                    div().h(px(50.)).w_full().into_any()
3481                })
3482                .w_full()
3483                .h_full()
3484            }
3485        }
3486
3487        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3488
3489        state.set_follow_mode(FollowMode::Tail);
3490
3491        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3492            view.clone().into_any_element()
3493        });
3494        assert!(state.is_following_tail());
3495
3496        // Scroll up — follow_tail should suspend (not fully disengage).
3497        cx.simulate_event(ScrollEvent {
3498            position: point(px(50.), px(100.)),
3499            delta: ScrollDelta::Pixels(point(px(0.), px(50.))),
3500            ..Default::default()
3501        });
3502        assert!(!state.is_following_tail());
3503
3504        // Scroll back down to the bottom.
3505        cx.simulate_event(ScrollEvent {
3506            position: point(px(50.), px(100.)),
3507            delta: ScrollDelta::Pixels(point(px(0.), px(-10000.))),
3508            ..Default::default()
3509        });
3510
3511        // After a paint, follow_tail should re-engage because the
3512        // layout confirmed we're at the true bottom.
3513        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3514            view.clone().into_any_element()
3515        });
3516        assert!(
3517            state.is_following_tail(),
3518            "follow_tail should re-engage after scrolling back to the bottom"
3519        );
3520    }
3521
3522    /// When an item is spliced to unmeasured (0px) while follow_tail
3523    /// is suspended, the re-engagement check should still work correctly
3524    #[gpui::test]
3525    fn test_follow_tail_reengagement_not_fooled_by_unmeasured_items(cx: &mut TestAppContext) {
3526        let cx = cx.add_empty_window();
3527
3528        // 20 items × 50px = 1000px total, 200px viewport, 1000px
3529        // overdraw so all items get measured during the follow_tail
3530        // paint (matching realistic production settings).
3531        let state = ListState::new(20, crate::ListAlignment::Top, px(1000.));
3532
3533        struct TestView(ListState);
3534        impl Render for TestView {
3535            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3536                list(self.0.clone(), |_, _, _| {
3537                    div().h(px(50.)).w_full().into_any()
3538                })
3539                .w_full()
3540                .h_full()
3541            }
3542        }
3543
3544        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3545
3546        state.set_follow_mode(FollowMode::Tail);
3547
3548        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3549            view.clone().into_any_element()
3550        });
3551        assert!(state.is_following_tail());
3552
3553        // Scroll up a meaningful amount — suspends follow_tail.
3554        // 20 items × 50px = 1000px. viewport 200px. scroll_max = 800px.
3555        // Scrolling up 200px puts us at 600px, clearly not at bottom.
3556        cx.simulate_event(ScrollEvent {
3557            position: point(px(50.), px(100.)),
3558            delta: ScrollDelta::Pixels(point(px(0.), px(200.))),
3559            ..Default::default()
3560        });
3561        assert!(!state.is_following_tail());
3562
3563        // Invalidate the last item (simulates EntryUpdated calling
3564        // remeasure_items). This makes items.summary().height
3565        // temporarily wrong (0px for the invalidated item).
3566        state.remeasure_items(19..20);
3567
3568        // Paint — layout re-measures the invalidated item with its true
3569        // height. The re-engagement check uses these fresh measurements.
3570        // Since we scrolled 200px up from the 800px max, we're at
3571        // ~600px — NOT at the bottom, so follow_tail should NOT
3572        // re-engage.
3573        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3574            view.clone().into_any_element()
3575        });
3576        assert!(
3577            !state.is_following_tail(),
3578            "follow_tail should not falsely re-engage due to an unmeasured item \
3579             reducing items.summary().height"
3580        );
3581    }
3582
3583    #[gpui::test]
3584    fn test_follow_tail_reengages_after_scrollbar_disengagement(cx: &mut TestAppContext) {
3585        let cx = cx.add_empty_window();
3586
3587        // 10 items × 50px = 500px total, 200px viewport, scroll_max = 300px.
3588        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3589
3590        struct TestView(ListState);
3591        impl Render for TestView {
3592            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3593                list(self.0.clone(), |_, _, _| {
3594                    div().h(px(50.)).w_full().into_any()
3595                })
3596                .w_full()
3597                .h_full()
3598            }
3599        }
3600
3601        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3602
3603        state.set_follow_mode(FollowMode::Tail);
3604        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3605            view.clone().into_any_element()
3606        });
3607        assert!(state.is_following_tail());
3608
3609        // Drag the scrollbar up to the middle — follow_tail should suspend.
3610        state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3611        assert!(!state.is_following_tail());
3612
3613        // Drag the scrollbar back to the bottom — follow_tail should re-engage
3614        // on the next paint.
3615        state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
3616        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3617            view.into_any_element()
3618        });
3619        assert!(
3620            state.is_following_tail(),
3621            "follow_tail should re-engage after scrolling back to the bottom via the scrollbar"
3622        );
3623    }
3624
3625    #[gpui::test]
3626    fn test_follow_tail_reengages_after_scrollbar_drag_to_bottom_while_growing(
3627        cx: &mut TestAppContext,
3628    ) {
3629        let cx = cx.add_empty_window();
3630
3631        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3632
3633        struct TestView(ListState);
3634        impl Render for TestView {
3635            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3636                list(self.0.clone(), |_, _, _| {
3637                    div().h(px(50.)).w_full().into_any()
3638                })
3639                .w_full()
3640                .h_full()
3641            }
3642        }
3643
3644        let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3645
3646        state.set_follow_mode(FollowMode::Tail);
3647        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3648            view.clone().into_any_element()
3649        });
3650        assert!(state.is_following_tail());
3651
3652        state.scrollbar_drag_started();
3653
3654        state.splice(10..10, 10);
3655        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3656            view.clone().into_any_element()
3657        });
3658
3659        state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
3660        state.scrollbar_drag_ended();
3661
3662        cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3663            view.into_any_element()
3664        });
3665
3666        assert!(
3667            state.is_following_tail(),
3668            "follow_tail should re-engage when the user drags the scrollbar to \
3669             the bottom of its track, even when content has grown during the drag \
3670             (so frozen_bottom < live_bottom)"
3671        );
3672    }
3673
3674    #[gpui::test]
3675    fn test_horizontal_padding_insets_items(cx: &mut TestAppContext) {
3676        let cx = cx.add_empty_window();
3677
3678        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3679        let item_bounds = Rc::new(RefCell::new(Vec::new()));
3680
3681        struct TestView {
3682            state: ListState,
3683            item_bounds: Rc<RefCell<Vec<Bounds<Pixels>>>>,
3684        }
3685        impl Render for TestView {
3686            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3687                let item_bounds = self.item_bounds.clone();
3688                list(self.state.clone(), move |_, _, _| {
3689                    let item_bounds = item_bounds.clone();
3690                    canvas(
3691                        move |bounds, _, _| item_bounds.borrow_mut().push(bounds),
3692                        |_, _, _, _| {},
3693                    )
3694                    .w_full()
3695                    .aspect_ratio(2.)
3696                    .into_any()
3697                })
3698                .pl(px(10.))
3699                .pr(px(30.))
3700                .w_full()
3701                .h_full()
3702            }
3703        }
3704
3705        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
3706            cx.new(|_| TestView {
3707                state: state.clone(),
3708                item_bounds: item_bounds.clone(),
3709            })
3710            .into_any_element()
3711        });
3712
3713        for bounds in item_bounds.borrow().iter() {
3714            assert_eq!(bounds.origin.x, px(10.));
3715            assert_eq!(bounds.size.width, px(60.));
3716        }
3717        // Each item is 60px wide, so 30px tall: 300px in total.
3718        assert_eq!(state.max_offset_for_scrollbar().y, px(200.));
3719    }
3720
3721    #[gpui::test]
3722    fn test_inferred_width_includes_horizontal_padding(cx: &mut TestAppContext) {
3723        let cx = cx.add_empty_window();
3724
3725        let state = ListState::new(2, crate::ListAlignment::Top, px(10.));
3726        let full_width_item_bounds = Rc::new(RefCell::new(None));
3727
3728        struct TestView {
3729            state: ListState,
3730            full_width_item_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
3731        }
3732        impl Render for TestView {
3733            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3734                let full_width_item_bounds = self.full_width_item_bounds.clone();
3735                div().flex().size_full().child(
3736                    list(self.state.clone(), move |ix, _, _| {
3737                        if ix == 0 {
3738                            div().w(px(50.)).h(px(20.)).into_any()
3739                        } else {
3740                            let full_width_item_bounds = full_width_item_bounds.clone();
3741                            canvas(
3742                                move |bounds, _, _| {
3743                                    *full_width_item_bounds.borrow_mut() = Some(bounds)
3744                                },
3745                                |_, _, _, _| {},
3746                            )
3747                            .h(px(20.))
3748                            .w_full()
3749                            .into_any()
3750                        }
3751                    })
3752                    .with_sizing_behavior(ListSizingBehavior::Infer)
3753                    .pl(px(10.))
3754                    .pr(px(30.))
3755                    .h_full(),
3756                )
3757            }
3758        }
3759
3760        cx.draw(point(px(0.), px(0.)), size(px(200.), px(100.)), |_, cx| {
3761            cx.new(|_| TestView {
3762                state: state.clone(),
3763                full_width_item_bounds: full_width_item_bounds.clone(),
3764            })
3765            .into_any_element()
3766        });
3767
3768        let bounds = full_width_item_bounds
3769            .borrow()
3770            .expect("item 1 was not painted");
3771        assert_eq!(bounds.origin.x, px(10.));
3772        assert_eq!(bounds.size.width, px(50.));
3773    }
3774
3775    #[gpui::test]
3776    fn test_autoscroll_above_item_top_with_horizontal_padding(cx: &mut TestAppContext) {
3777        let cx = cx.add_empty_window();
3778
3779        let state = ListState::new(5, crate::ListAlignment::Top, px(0.));
3780        state.scroll_to(gpui::ListOffset {
3781            item_ix: 2,
3782            offset_in_item: px(0.),
3783        });
3784
3785        struct TestView(ListState);
3786        impl Render for TestView {
3787            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3788                list(self.0.clone(), |ix, _, _| {
3789                    if ix == 2 {
3790                        canvas(
3791                            |bounds, window, _| {
3792                                window.request_autoscroll(Bounds::from_corners(
3793                                    point(bounds.left(), bounds.top() - px(30.)),
3794                                    point(bounds.right(), bounds.top() + px(5.)),
3795                                ));
3796                            },
3797                            |_, _, _, _| {},
3798                        )
3799                        .w_full()
3800                        .aspect_ratio(2.)
3801                        .into_any()
3802                    } else {
3803                        div().w_full().aspect_ratio(2.).into_any()
3804                    }
3805                })
3806                .pl(px(10.))
3807                .pr(px(30.))
3808                .w_full()
3809                .h_full()
3810            }
3811        }
3812
3813        cx.draw(point(px(0.), px(0.)), size(px(100.), px(60.)), |_, cx| {
3814            cx.new(|_| TestView(state.clone())).into_any_element()
3815        });
3816
3817        // Items are 60px wide, so 30px tall: 30px above item 2 is the top of item 1.
3818        let scroll_top = state.logical_scroll_top();
3819        assert_eq!(scroll_top.item_ix, 1);
3820        assert_eq!(scroll_top.offset_in_item, px(0.));
3821    }
3822
3823    #[gpui::test]
3824    fn test_horizontal_padding_change_remeasures_items(cx: &mut TestAppContext) {
3825        let cx = cx.add_empty_window();
3826
3827        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3828
3829        struct TestView {
3830            state: ListState,
3831            padding_right: Pixels,
3832        }
3833        impl Render for TestView {
3834            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3835                list(self.state.clone(), |_, _, _| {
3836                    div().w_full().aspect_ratio(2.).into_any()
3837                })
3838                .pl(px(10.))
3839                .pr(self.padding_right)
3840                .w_full()
3841                .h_full()
3842            }
3843        }
3844
3845        // The list width stays at 100px while the padding shrinks, so items go
3846        // from 60px wide (30px tall) to 80px wide (40px tall).
3847        for (padding_right, expected_max_offset) in [(px(30.), px(200.)), (px(10.), px(300.))] {
3848            cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
3849                cx.new(|_| TestView {
3850                    state: state.clone(),
3851                    padding_right,
3852                })
3853                .into_any_element()
3854            });
3855            assert_eq!(state.max_offset_for_scrollbar().y, expected_max_offset);
3856        }
3857    }
3858
3859    #[gpui::test]
3860    fn test_border_and_padding_inset_items(cx: &mut TestAppContext) {
3861        let cx = cx.add_empty_window();
3862
3863        let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3864        let item_bounds = Rc::new(RefCell::new(Vec::new()));
3865
3866        struct TestView {
3867            state: ListState,
3868            item_bounds: Rc<RefCell<Vec<Bounds<Pixels>>>>,
3869        }
3870        impl Render for TestView {
3871            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3872                let item_bounds = self.item_bounds.clone();
3873                list(self.state.clone(), move |_, _, _| {
3874                    let item_bounds = item_bounds.clone();
3875                    canvas(
3876                        move |bounds, _, _| item_bounds.borrow_mut().push(bounds),
3877                        |_, _, _, _| {},
3878                    )
3879                    .w_full()
3880                    .aspect_ratio(2.)
3881                    .into_any()
3882                })
3883                .border_l_4()
3884                .pl(px(6.))
3885                .border_r_8()
3886                .pr(px(22.))
3887                .w_full()
3888                .h_full()
3889            }
3890        }
3891
3892        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
3893            cx.new(|_| TestView {
3894                state: state.clone(),
3895                item_bounds: item_bounds.clone(),
3896            })
3897            .into_any_element()
3898        });
3899
3900        let painted_bounds = item_bounds.borrow();
3901        assert!(!painted_bounds.is_empty());
3902        for bounds in painted_bounds.iter() {
3903            assert_eq!(bounds.origin.x, px(10.));
3904            assert_eq!(bounds.size.width, px(60.));
3905        }
3906        assert_eq!(state.max_offset_for_scrollbar().y, px(200.));
3907
3908        let reported_bounds = state.bounds_for_item(0).expect("item 0 should be measured");
3909        assert_eq!(reported_bounds.origin.x, px(10.));
3910        assert_eq!(reported_bounds.size.width, px(60.));
3911    }
3912
3913    fn draw_list(
3914        state: &ListState,
3915        viewport_height: f32,
3916        render_item: impl Fn(usize) -> AnyElement + 'static,
3917        cx: &mut VisualTestContext,
3918    ) {
3919        cx.draw(
3920            point(px(0.), px(0.)),
3921            size(px(100.), px(viewport_height)),
3922            |_, cx| {
3923                cx.new(|_| TestView {
3924                    state: state.clone(),
3925                    render_item: Rc::new(render_item),
3926                })
3927                .into_any_element()
3928            },
3929        );
3930    }
3931
3932    fn painted_item(
3933        index: usize,
3934        height: f32,
3935        painted: &Rc<RefCell<Vec<(usize, Pixels, Pixels)>>>,
3936    ) -> AnyElement {
3937        let painted = painted.clone();
3938        canvas(
3939            |_, _, _| {},
3940            move |bounds, _, _, _| {
3941                painted
3942                    .borrow_mut()
3943                    .push((index, bounds.top(), bounds.bottom()));
3944            },
3945        )
3946        .h(px(height))
3947        .w_full()
3948        .into_any()
3949    }
3950
3951    fn item_readiness(state: &ListState, ready: bool) -> Rc<Cell<bool>> {
3952        let ready = Rc::new(Cell::new(ready));
3953        state.set_item_measurement_readiness({
3954            let ready = ready.clone();
3955            move |_, _| ready.get()
3956        });
3957        ready
3958    }
3959
3960    fn list_offset(item_ix: usize, offset: f32) -> ListOffset {
3961        ListOffset {
3962            item_ix,
3963            offset_in_item: px(offset),
3964        }
3965    }
3966
3967    struct TestView {
3968        state: ListState,
3969        render_item: Rc<dyn Fn(usize) -> AnyElement>,
3970    }
3971
3972    impl Render for TestView {
3973        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3974            let render_item = self.render_item.clone();
3975            list(self.state.clone(), move |index, _, _| render_item(index))
3976                .w_full()
3977                .h_full()
3978        }
3979    }
3980
3981    struct TestListView(ListState);
3982    impl Render for TestListView {
3983        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3984            list(self.0.clone(), |_, _, _| {
3985                div().h(px(20.)).w_full().into_any()
3986            })
3987            .w_full()
3988            .h_full()
3989        }
3990    }
3991}