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