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