1//! A list element that can be used to render a large number of differently sized elements
2//! efficiently. Clients of this API need to ensure that elements outside of the scrolled
3//! area do not change their height for this element to function correctly. If your elements
4//! do change height, notify the list element via [`ListState::splice`] or [`ListState::reset`].
5//! In order to minimize re-renders, this element's state is stored intrusively
6//! on your own views, so that your code can coordinate directly with the list element's cached state.
7//!
8//! If all of your elements are the same height, see [`crate::UniformList`] for a simpler API
9
10use crate::{
11 AnyElement, App, AvailableSpace, Bounds, ContentMask, DispatchPhase, Edges, Element, EntityId,
12 FocusHandle, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, IntoElement,
13 Overflow, Pixels, Point, ScrollDelta, ScrollWheelEvent, Size, Style, StyleRefinement, Styled,
14 Window, point, px, size,
15};
16use collections::VecDeque;
17use refineable::Refineable as _;
18use std::{cell::RefCell, ops::Range, rc::Rc};
19use sum_tree::{Bias, Dimensions, SumTree};
20
21type RenderItemFn = dyn FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static;
22
23/// Construct a new list element
24pub fn list(
25 state: ListState,
26 render_item: impl FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static,
27) -> List {
28 List {
29 state,
30 render_item: Box::new(render_item),
31 style: StyleRefinement::default(),
32 sizing_behavior: ListSizingBehavior::default(),
33 }
34}
35
36/// A list element
37pub struct List {
38 state: ListState,
39 render_item: Box<RenderItemFn>,
40 style: StyleRefinement,
41 sizing_behavior: ListSizingBehavior,
42}
43
44impl List {
45 /// Set the sizing behavior for the list.
46 pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
47 self.sizing_behavior = behavior;
48 self
49 }
50}
51
52/// The list state that views must hold on behalf of the list element.
53#[derive(Clone)]
54pub struct ListState(Rc<RefCell<StateInner>>);
55
56impl std::fmt::Debug for ListState {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 f.write_str("ListState")
59 }
60}
61
62struct StateInner {
63 last_layout_bounds: Option<Bounds<Pixels>>,
64 last_padding: Option<Edges<Pixels>>,
65 items: SumTree<ListItem>,
66 logical_scroll_top: Option<ListOffset>,
67 alignment: ListAlignment,
68 overdraw: Pixels,
69 reset: bool,
70 #[allow(clippy::type_complexity)]
71 scroll_handler: Option<Box<dyn FnMut(&ListScrollEvent, &mut Window, &mut App)>>,
72 scrollbar_drag_start_height: Option<Pixels>,
73 measuring_behavior: ListMeasuringBehavior,
74 pending_scroll: Option<PendingScrollFraction>,
75 follow_state: FollowState,
76}
77
78/// Keeps track of a fractional scroll position within an item for restoration
79/// after remeasurement.
80struct PendingScrollFraction {
81 /// The index of the item to scroll within.
82 item_ix: usize,
83 /// Fractional offset (0.0 to 1.0) within the item's height.
84 fraction: f32,
85}
86
87/// Controls whether the list automatically follows new content at the end.
88#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
89pub enum FollowMode {
90 /// Normal scrolling β no automatic following.
91 #[default]
92 Normal,
93 /// The list should auto-scroll along with the tail, when scrolled to bottom.
94 Tail,
95}
96
97#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
98enum FollowState {
99 #[default]
100 Normal,
101 Tail {
102 is_following: bool,
103 },
104}
105
106impl FollowState {
107 fn is_following(&self) -> bool {
108 matches!(self, FollowState::Tail { is_following: true })
109 }
110
111 fn has_stopped_following(&self) -> bool {
112 matches!(
113 self,
114 FollowState::Tail {
115 is_following: false
116 }
117 )
118 }
119
120 fn start_following(&mut self) {
121 if let FollowState::Tail {
122 is_following: false,
123 } = self
124 {
125 *self = FollowState::Tail { is_following: true };
126 }
127 }
128}
129
130/// Whether the list is scrolling from top to bottom or bottom to top.
131#[derive(Clone, Copy, Debug, Eq, PartialEq)]
132pub enum ListAlignment {
133 /// The list is scrolling from top to bottom, like most lists.
134 Top,
135 /// The list is scrolling from bottom to top, like a chat log.
136 Bottom,
137}
138
139/// A scroll event that has been converted to be in terms of the list's items.
140pub struct ListScrollEvent {
141 /// The range of items currently visible in the list, after applying the scroll event.
142 pub visible_range: Range<usize>,
143
144 /// The number of items that are currently visible in the list, after applying the scroll event.
145 pub count: usize,
146
147 /// Whether the list has been scrolled.
148 pub is_scrolled: bool,
149
150 /// Whether the list is currently in follow-tail mode (auto-scrolling to end).
151 pub is_following_tail: bool,
152}
153
154/// The sizing behavior to apply during layout.
155#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
156pub enum ListSizingBehavior {
157 /// The list should calculate its size based on the size of its items.
158 Infer,
159 /// The list should not calculate a fixed size.
160 #[default]
161 Auto,
162}
163
164/// The measuring behavior to apply during layout.
165#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
166pub enum ListMeasuringBehavior {
167 /// Measure all items in the list.
168 /// Note: This can be expensive for the first frame in a large list.
169 Measure(bool),
170 /// Only measure visible items
171 #[default]
172 Visible,
173}
174
175impl ListMeasuringBehavior {
176 fn reset(&mut self) {
177 match self {
178 ListMeasuringBehavior::Measure(has_measured) => *has_measured = false,
179 ListMeasuringBehavior::Visible => {}
180 }
181 }
182}
183
184/// The horizontal sizing behavior to apply during layout.
185#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
186pub enum ListHorizontalSizingBehavior {
187 /// List items' width can never exceed the width of the list.
188 #[default]
189 FitList,
190 /// List items' width may go over the width of the list, if any item is wider.
191 Unconstrained,
192}
193
194struct LayoutItemsResponse {
195 max_item_width: Pixels,
196 scroll_top: ListOffset,
197 item_layouts: VecDeque<ItemLayout>,
198}
199
200struct ItemLayout {
201 index: usize,
202 element: AnyElement,
203 size: Size<Pixels>,
204}
205
206/// Frame state used by the [List] element after layout.
207pub struct ListPrepaintState {
208 hitbox: Hitbox,
209 layout: LayoutItemsResponse,
210}
211
212#[derive(Clone)]
213enum ListItem {
214 Unmeasured {
215 size_hint: Option<Size<Pixels>>,
216 focus_handle: Option<FocusHandle>,
217 },
218 Measured {
219 size: Size<Pixels>,
220 focus_handle: Option<FocusHandle>,
221 },
222}
223
224impl ListItem {
225 fn size(&self) -> Option<Size<Pixels>> {
226 if let ListItem::Measured { size, .. } = self {
227 Some(*size)
228 } else {
229 None
230 }
231 }
232
233 fn size_hint(&self) -> Option<Size<Pixels>> {
234 match self {
235 ListItem::Measured { size, .. } => Some(*size),
236 ListItem::Unmeasured { size_hint, .. } => *size_hint,
237 }
238 }
239
240 fn focus_handle(&self) -> Option<FocusHandle> {
241 match self {
242 ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
243 focus_handle.clone()
244 }
245 }
246 }
247
248 fn contains_focused(&self, window: &Window, cx: &App) -> bool {
249 match self {
250 ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
251 focus_handle
252 .as_ref()
253 .is_some_and(|handle| handle.contains_focused(window, cx))
254 }
255 }
256 }
257}
258
259#[derive(Clone, Debug, Default, PartialEq)]
260struct ListItemSummary {
261 count: usize,
262 rendered_count: usize,
263 unrendered_count: usize,
264 height: Pixels,
265 has_focus_handles: bool,
266}
267
268#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
269struct Count(usize);
270
271#[derive(Clone, Debug, Default)]
272struct Height(Pixels);
273
274impl ListState {
275 /// Construct a new list state, for storage on a view.
276 ///
277 /// The overdraw parameter controls how much extra space is rendered
278 /// above and below the visible area. Elements within this area will
279 /// be measured even though they are not visible. This can help ensure
280 /// that the list doesn't flicker or pop in when scrolling.
281 pub fn new(item_count: usize, alignment: ListAlignment, overdraw: Pixels) -> Self {
282 let this = Self(Rc::new(RefCell::new(StateInner {
283 last_layout_bounds: None,
284 last_padding: None,
285 items: SumTree::default(),
286 logical_scroll_top: None,
287 alignment,
288 overdraw,
289 scroll_handler: None,
290 reset: false,
291 scrollbar_drag_start_height: None,
292 measuring_behavior: ListMeasuringBehavior::default(),
293 pending_scroll: None,
294 follow_state: FollowState::default(),
295 })));
296 this.splice(0..0, item_count);
297 this
298 }
299
300 /// Set the list to measure all items in the list in the first layout phase.
301 ///
302 /// This is useful for ensuring that the scrollbar size is correct instead of based on only rendered elements.
303 pub fn measure_all(self) -> Self {
304 self.0.borrow_mut().measuring_behavior = ListMeasuringBehavior::Measure(false);
305 self
306 }
307
308 /// Reset this instantiation of the list state.
309 ///
310 /// Note that this will cause scroll events to be dropped until the next paint.
311 pub fn reset(&self, element_count: usize) {
312 let old_count = {
313 let state = &mut *self.0.borrow_mut();
314 state.reset = true;
315 state.measuring_behavior.reset();
316 state.logical_scroll_top = None;
317 state.scrollbar_drag_start_height = None;
318 state.items.summary().count
319 };
320
321 self.splice(0..old_count, element_count);
322 }
323
324 /// Remeasure all items while preserving proportional scroll position.
325 ///
326 /// Use this when item heights may have changed (e.g., font size changes)
327 /// but the number and identity of items remains the same.
328 pub fn remeasure(&self) {
329 let count = self.item_count();
330 self.remeasure_items(0..count);
331 }
332
333 /// Mark items in `range` as needing remeasurement while preserving
334 /// the current scroll position. Unlike [`Self::splice`], this does
335 /// not change the number of items or blow away `logical_scroll_top`.
336 ///
337 /// Use this when an item's content has changed and its rendered
338 /// height may be different (e.g., streaming text, tool results
339 /// loading), but the item itself still exists at the same index.
340 pub fn remeasure_items(&self, range: Range<usize>) {
341 let state = &mut *self.0.borrow_mut();
342
343 // If the scroll-top item falls within the remeasured range,
344 // store a fractional offset so the layout can restore the
345 // proportional scroll position after the item is re-rendered
346 // at its new height.
347 if let Some(scroll_top) = state.logical_scroll_top {
348 if range.contains(&scroll_top.item_ix) {
349 let mut cursor = state.items.cursor::<Count>(());
350 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
351
352 if let Some(item) = cursor.item() {
353 if let Some(size) = item.size() {
354 let fraction = if size.height.0 > 0.0 {
355 (scroll_top.offset_in_item.0 / size.height.0).clamp(0.0, 1.0)
356 } else {
357 0.0
358 };
359
360 state.pending_scroll = Some(PendingScrollFraction {
361 item_ix: scroll_top.item_ix,
362 fraction,
363 });
364 }
365 }
366 }
367 }
368
369 // Rebuild the tree, replacing items in the range with
370 // Unmeasured copies that keep their focus handles.
371 let new_items = {
372 let mut cursor = state.items.cursor::<Count>(());
373 let mut new_items = cursor.slice(&Count(range.start), Bias::Right);
374 let invalidated = cursor.slice(&Count(range.end), Bias::Right);
375 new_items.extend(
376 invalidated.iter().map(|item| ListItem::Unmeasured {
377 size_hint: item.size_hint(),
378 focus_handle: item.focus_handle(),
379 }),
380 (),
381 );
382 new_items.append(cursor.suffix(), ());
383 new_items
384 };
385 state.items = new_items;
386 state.measuring_behavior.reset();
387 }
388
389 /// The number of items in this list.
390 pub fn item_count(&self) -> usize {
391 self.0.borrow().items.summary().count
392 }
393
394 /// Inform the list state that the items in `old_range` have been replaced
395 /// by `count` new items that must be recalculated.
396 pub fn splice(&self, old_range: Range<usize>, count: usize) {
397 self.splice_focusable(old_range, (0..count).map(|_| None))
398 }
399
400 /// Register with the list state that the items in `old_range` have been replaced
401 /// by new items. As opposed to [`Self::splice`], this method allows an iterator of optional focus handles
402 /// to be supplied to properly integrate with items in the list that can be focused. If a focused item
403 /// is scrolled out of view, the list will continue to render it to allow keyboard interaction.
404 pub fn splice_focusable(
405 &self,
406 old_range: Range<usize>,
407 focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
408 ) {
409 let state = &mut *self.0.borrow_mut();
410
411 let mut old_items = state.items.cursor::<Count>(());
412 let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right);
413 old_items.seek_forward(&Count(old_range.end), Bias::Right);
414
415 let mut spliced_count = 0;
416 new_items.extend(
417 focus_handles.into_iter().map(|focus_handle| {
418 spliced_count += 1;
419 ListItem::Unmeasured {
420 size_hint: None,
421 focus_handle,
422 }
423 }),
424 (),
425 );
426 new_items.append(old_items.suffix(), ());
427 drop(old_items);
428 state.items = new_items;
429
430 if let Some(ListOffset {
431 item_ix,
432 offset_in_item,
433 }) = state.logical_scroll_top.as_mut()
434 {
435 if old_range.contains(item_ix) {
436 *item_ix = old_range.start;
437 *offset_in_item = px(0.);
438 } else if old_range.end <= *item_ix {
439 *item_ix = *item_ix - (old_range.end - old_range.start) + spliced_count;
440 }
441 }
442 }
443
444 /// Set a handler that will be called when the list is scrolled.
445 pub fn set_scroll_handler(
446 &self,
447 handler: impl FnMut(&ListScrollEvent, &mut Window, &mut App) + 'static,
448 ) {
449 self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
450 }
451
452 /// Get the current scroll offset, in terms of the list's items.
453 pub fn logical_scroll_top(&self) -> ListOffset {
454 self.0.borrow().logical_scroll_top()
455 }
456
457 /// Scroll the list by the given offset
458 pub fn scroll_by(&self, distance: Pixels) {
459 if distance == px(0.) {
460 return;
461 }
462
463 let current_offset = self.logical_scroll_top();
464 let state = &mut *self.0.borrow_mut();
465 let mut cursor = state.items.cursor::<ListItemSummary>(());
466 cursor.seek(&Count(current_offset.item_ix), Bias::Right);
467
468 let start_pixel_offset = cursor.start().height + current_offset.offset_in_item;
469 let new_pixel_offset = (start_pixel_offset + distance).max(px(0.));
470 if new_pixel_offset > start_pixel_offset {
471 cursor.seek_forward(&Height(new_pixel_offset), Bias::Right);
472 } else {
473 cursor.seek(&Height(new_pixel_offset), Bias::Right);
474 }
475
476 state.logical_scroll_top = Some(ListOffset {
477 item_ix: cursor.start().count,
478 offset_in_item: new_pixel_offset - cursor.start().height,
479 });
480 }
481
482 /// Scroll the list to the very end (past the last item).
483 ///
484 /// Unlike [`scroll_to_reveal_item`], this uses the total item count as the
485 /// anchor, so the list's layout pass will walk backwards from the end and
486 /// always show the bottom of the last item β even when that item is still
487 /// growing (e.g. during streaming).
488 pub fn scroll_to_end(&self) {
489 let state = &mut *self.0.borrow_mut();
490 let item_count = state.items.summary().count;
491 state.logical_scroll_top = Some(ListOffset {
492 item_ix: item_count,
493 offset_in_item: px(0.),
494 });
495 }
496
497 /// Set the follow mode for the list. In `Tail` mode, the list
498 /// will auto-scroll to the end and re-engage after the user
499 /// scrolls back to the bottom. In `Normal` mode, no automatic
500 /// following occurs.
501 pub fn set_follow_mode(&self, mode: FollowMode) {
502 let state = &mut *self.0.borrow_mut();
503
504 match mode {
505 FollowMode::Normal => {
506 state.follow_state = FollowState::Normal;
507 }
508 FollowMode::Tail => {
509 state.follow_state = FollowState::Tail { is_following: true };
510 if matches!(mode, FollowMode::Tail) {
511 let item_count = state.items.summary().count;
512 state.logical_scroll_top = Some(ListOffset {
513 item_ix: item_count,
514 offset_in_item: px(0.),
515 });
516 }
517 }
518 }
519 }
520
521 /// Returns whether the list is currently actively following the
522 /// tail (snapping to the end on each layout).
523 pub fn is_following_tail(&self) -> bool {
524 matches!(
525 self.0.borrow().follow_state,
526 FollowState::Tail { is_following: true }
527 )
528 }
529
530 /// Scroll the list to the given offset
531 pub fn scroll_to(&self, mut scroll_top: ListOffset) {
532 let state = &mut *self.0.borrow_mut();
533 let item_count = state.items.summary().count;
534 if scroll_top.item_ix >= item_count {
535 scroll_top.item_ix = item_count;
536 scroll_top.offset_in_item = px(0.);
537 }
538
539 state.logical_scroll_top = Some(scroll_top);
540 }
541
542 /// Scroll the list to the given item, such that the item is fully visible.
543 pub fn scroll_to_reveal_item(&self, ix: usize) {
544 let state = &mut *self.0.borrow_mut();
545
546 let mut scroll_top = state.logical_scroll_top();
547 let height = state
548 .last_layout_bounds
549 .map_or(px(0.), |bounds| bounds.size.height);
550 let padding = state.last_padding.unwrap_or_default();
551
552 if ix <= scroll_top.item_ix {
553 scroll_top.item_ix = ix;
554 scroll_top.offset_in_item = px(0.);
555 } else {
556 let mut cursor = state.items.cursor::<ListItemSummary>(());
557 cursor.seek(&Count(ix + 1), Bias::Right);
558 let bottom = cursor.start().height + padding.top;
559 let goal_top = px(0.).max(bottom - height + padding.bottom);
560
561 cursor.seek(&Height(goal_top), Bias::Left);
562 let start_ix = cursor.start().count;
563 let start_item_top = cursor.start().height;
564
565 if start_ix >= scroll_top.item_ix {
566 scroll_top.item_ix = start_ix;
567 scroll_top.offset_in_item = goal_top - start_item_top;
568 }
569 }
570
571 state.logical_scroll_top = Some(scroll_top);
572 }
573
574 /// Get the bounds for the given item in window coordinates, if it's
575 /// been rendered.
576 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
577 let state = &*self.0.borrow();
578
579 let bounds = state.last_layout_bounds.unwrap_or_default();
580 let scroll_top = state.logical_scroll_top();
581 if ix < scroll_top.item_ix {
582 return None;
583 }
584
585 let mut cursor = state.items.cursor::<Dimensions<Count, Height>>(());
586 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
587
588 let scroll_top = cursor.start().1.0 + scroll_top.offset_in_item;
589
590 cursor.seek_forward(&Count(ix), Bias::Right);
591 if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
592 let &Dimensions(Count(count), Height(top), _) = cursor.start();
593 if count == ix {
594 let top = bounds.top() + top - scroll_top;
595 return Some(Bounds::from_corners(
596 point(bounds.left(), top),
597 point(bounds.right(), top + size.height),
598 ));
599 }
600 }
601 None
602 }
603
604 /// Call this method when the user starts dragging the scrollbar.
605 ///
606 /// This will prevent the height reported to the scrollbar from changing during the drag
607 /// as items in the overdraw get measured, and help offset scroll position changes accordingly.
608 pub fn scrollbar_drag_started(&self) {
609 let mut state = self.0.borrow_mut();
610 state.scrollbar_drag_start_height = Some(state.items.summary().height);
611 }
612
613 /// Called when the user stops dragging the scrollbar.
614 ///
615 /// See `scrollbar_drag_started`.
616 pub fn scrollbar_drag_ended(&self) {
617 self.0.borrow_mut().scrollbar_drag_start_height.take();
618 }
619
620 /// Set the offset from the scrollbar
621 pub fn set_offset_from_scrollbar(&self, point: Point<Pixels>) {
622 self.0.borrow_mut().set_offset_from_scrollbar(point);
623 }
624
625 /// Returns the maximum scroll offset according to the items we have measured.
626 /// This value remains constant while dragging to prevent the scrollbar from moving away unexpectedly.
627 pub fn max_offset_for_scrollbar(&self) -> Point<Pixels> {
628 let state = self.0.borrow();
629 point(Pixels::ZERO, state.max_scroll_offset())
630 }
631
632 /// Returns the current scroll offset adjusted for the scrollbar
633 pub fn scroll_px_offset_for_scrollbar(&self) -> Point<Pixels> {
634 let state = &self.0.borrow();
635
636 if state.logical_scroll_top.is_none() && state.alignment == ListAlignment::Bottom {
637 return Point::new(px(0.), -state.max_scroll_offset());
638 }
639
640 let logical_scroll_top = state.logical_scroll_top();
641
642 let mut cursor = state.items.cursor::<ListItemSummary>(());
643 let summary: ListItemSummary =
644 cursor.summary(&Count(logical_scroll_top.item_ix), Bias::Right);
645 let content_height = state.items.summary().height;
646 let drag_offset =
647 // if dragging the scrollbar, we want to offset the point if the height changed
648 content_height - state.scrollbar_drag_start_height.unwrap_or(content_height);
649 let offset = summary.height + logical_scroll_top.offset_in_item - drag_offset;
650
651 Point::new(px(0.), -offset)
652 }
653
654 /// Return the bounds of the viewport in pixels.
655 pub fn viewport_bounds(&self) -> Bounds<Pixels> {
656 self.0.borrow().last_layout_bounds.unwrap_or_default()
657 }
658}
659
660impl StateInner {
661 fn max_scroll_offset(&self) -> Pixels {
662 let bounds = self.last_layout_bounds.unwrap_or_default();
663 let height = self
664 .scrollbar_drag_start_height
665 .unwrap_or_else(|| self.items.summary().height);
666 (height - bounds.size.height).max(px(0.))
667 }
668
669 fn visible_range(
670 items: &SumTree<ListItem>,
671 height: Pixels,
672 scroll_top: &ListOffset,
673 ) -> Range<usize> {
674 let mut cursor = items.cursor::<ListItemSummary>(());
675 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
676 let start_y = cursor.start().height + scroll_top.offset_in_item;
677 cursor.seek_forward(&Height(start_y + height), Bias::Left);
678 scroll_top.item_ix..cursor.start().count + 1
679 }
680
681 fn scroll(
682 &mut self,
683 scroll_top: &ListOffset,
684 height: Pixels,
685 delta: Point<Pixels>,
686 current_view: EntityId,
687 window: &mut Window,
688 cx: &mut App,
689 ) {
690 // Drop scroll events after a reset, since we can't calculate
691 // the new logical scroll top without the item heights
692 if self.reset {
693 return;
694 }
695
696 let padding = self.last_padding.unwrap_or_default();
697 let scroll_max =
698 (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
699 let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
700 .max(px(0.))
701 .min(scroll_max);
702
703 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
704 self.logical_scroll_top = None;
705 } else {
706 let (start, ..) =
707 self.items
708 .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
709 let item_ix = start.count;
710 let offset_in_item = new_scroll_top - start.height;
711 self.logical_scroll_top = Some(ListOffset {
712 item_ix,
713 offset_in_item,
714 });
715 }
716
717 if let FollowState::Tail { is_following } = &mut self.follow_state {
718 if delta.y > px(0.) {
719 *is_following = false;
720 }
721 }
722
723 if let Some(handler) = self.scroll_handler.as_mut() {
724 let visible_range = Self::visible_range(&self.items, height, scroll_top);
725 handler(
726 &ListScrollEvent {
727 visible_range,
728 count: self.items.summary().count,
729 is_scrolled: self.logical_scroll_top.is_some(),
730 is_following_tail: matches!(
731 self.follow_state,
732 FollowState::Tail { is_following: true }
733 ),
734 },
735 window,
736 cx,
737 );
738 }
739
740 cx.notify(current_view);
741 }
742
743 fn logical_scroll_top(&self) -> ListOffset {
744 self.logical_scroll_top
745 .unwrap_or_else(|| match self.alignment {
746 ListAlignment::Top => ListOffset {
747 item_ix: 0,
748 offset_in_item: px(0.),
749 },
750 ListAlignment::Bottom => ListOffset {
751 item_ix: self.items.summary().count,
752 offset_in_item: px(0.),
753 },
754 })
755 }
756
757 fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
758 let (start, ..) = self.items.find::<ListItemSummary, _>(
759 (),
760 &Count(logical_scroll_top.item_ix),
761 Bias::Right,
762 );
763 start.height + logical_scroll_top.offset_in_item
764 }
765
766 fn layout_all_items(
767 &mut self,
768 available_width: Pixels,
769 render_item: &mut RenderItemFn,
770 window: &mut Window,
771 cx: &mut App,
772 ) {
773 match &mut self.measuring_behavior {
774 ListMeasuringBehavior::Visible => {
775 return;
776 }
777 ListMeasuringBehavior::Measure(has_measured) => {
778 if *has_measured {
779 return;
780 }
781 *has_measured = true;
782 }
783 }
784
785 let mut cursor = self.items.cursor::<Count>(());
786 let available_item_space = size(
787 AvailableSpace::Definite(available_width),
788 AvailableSpace::MinContent,
789 );
790
791 let mut measured_items = Vec::default();
792
793 for (ix, item) in cursor.enumerate() {
794 let size = item.size().unwrap_or_else(|| {
795 let mut element = render_item(ix, window, cx);
796 element.layout_as_root(available_item_space, window, cx)
797 });
798
799 measured_items.push(ListItem::Measured {
800 size,
801 focus_handle: item.focus_handle(),
802 });
803 }
804
805 self.items = SumTree::from_iter(measured_items, ());
806 }
807
808 fn layout_items(
809 &mut self,
810 available_width: Option<Pixels>,
811 available_height: Pixels,
812 padding: &Edges<Pixels>,
813 render_item: &mut RenderItemFn,
814 window: &mut Window,
815 cx: &mut App,
816 ) -> LayoutItemsResponse {
817 let old_items = self.items.clone();
818 let mut measured_items = VecDeque::new();
819 let mut item_layouts = VecDeque::new();
820 let mut rendered_height = padding.top;
821 let mut max_item_width = px(0.);
822 let mut scroll_top = self.logical_scroll_top();
823
824 if self.follow_state.is_following() {
825 scroll_top = ListOffset {
826 item_ix: self.items.summary().count,
827 offset_in_item: px(0.),
828 };
829 self.logical_scroll_top = Some(scroll_top);
830 }
831
832 let mut rendered_focused_item = false;
833
834 let available_item_space = size(
835 available_width.map_or(AvailableSpace::MinContent, |width| {
836 AvailableSpace::Definite(width)
837 }),
838 AvailableSpace::MinContent,
839 );
840
841 let mut cursor = old_items.cursor::<Count>(());
842
843 // Render items after the scroll top, including those in the trailing overdraw
844 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
845 for (ix, item) in cursor.by_ref().enumerate() {
846 let visible_height = rendered_height - scroll_top.offset_in_item;
847 if visible_height >= available_height + self.overdraw {
848 break;
849 }
850
851 // Use the previously cached height and focus handle if available
852 let mut size = item.size();
853
854 // If we're within the visible area or the height wasn't cached, render and measure the item's element
855 if visible_height < available_height || size.is_none() {
856 let item_index = scroll_top.item_ix + ix;
857 let mut element = render_item(item_index, window, cx);
858 let element_size = element.layout_as_root(available_item_space, window, cx);
859 size = Some(element_size);
860
861 // If there's a pending scroll adjustment for the scroll-top
862 // item, apply it, ensuring proportional scroll position is
863 // maintained after re-measuring.
864 if ix == 0 {
865 if let Some(pending_scroll) = self.pending_scroll.take() {
866 if pending_scroll.item_ix == scroll_top.item_ix {
867 scroll_top.offset_in_item =
868 Pixels(pending_scroll.fraction * element_size.height.0);
869 self.logical_scroll_top = Some(scroll_top);
870 }
871 }
872 }
873
874 if visible_height < available_height {
875 item_layouts.push_back(ItemLayout {
876 index: item_index,
877 element,
878 size: element_size,
879 });
880 if item.contains_focused(window, cx) {
881 rendered_focused_item = true;
882 }
883 }
884 }
885
886 let size = size.unwrap();
887 rendered_height += size.height;
888 max_item_width = max_item_width.max(size.width);
889 measured_items.push_back(ListItem::Measured {
890 size,
891 focus_handle: item.focus_handle(),
892 });
893 }
894 rendered_height += padding.bottom;
895
896 // Prepare to start walking upward from the item at the scroll top.
897 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
898
899 // If the rendered items do not fill the visible region, then adjust
900 // the scroll top upward.
901 if rendered_height - scroll_top.offset_in_item < available_height {
902 while rendered_height < available_height {
903 cursor.prev();
904 if let Some(item) = cursor.item() {
905 let item_index = cursor.start().0;
906 let mut element = render_item(item_index, window, cx);
907 let element_size = element.layout_as_root(available_item_space, window, cx);
908 let focus_handle = item.focus_handle();
909 rendered_height += element_size.height;
910 measured_items.push_front(ListItem::Measured {
911 size: element_size,
912 focus_handle,
913 });
914 item_layouts.push_front(ItemLayout {
915 index: item_index,
916 element,
917 size: element_size,
918 });
919 if item.contains_focused(window, cx) {
920 rendered_focused_item = true;
921 }
922 } else {
923 break;
924 }
925 }
926
927 scroll_top = ListOffset {
928 item_ix: cursor.start().0,
929 offset_in_item: rendered_height - available_height,
930 };
931
932 match self.alignment {
933 ListAlignment::Top => {
934 scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
935 self.logical_scroll_top = Some(scroll_top);
936 }
937 ListAlignment::Bottom => {
938 scroll_top = ListOffset {
939 item_ix: cursor.start().0,
940 offset_in_item: rendered_height - available_height,
941 };
942 self.logical_scroll_top = None;
943 }
944 };
945 }
946
947 // Measure items in the leading overdraw
948 let mut leading_overdraw = scroll_top.offset_in_item;
949 while leading_overdraw < self.overdraw {
950 cursor.prev();
951 if let Some(item) = cursor.item() {
952 let size = if let ListItem::Measured { size, .. } = item {
953 *size
954 } else {
955 let mut element = render_item(cursor.start().0, window, cx);
956 element.layout_as_root(available_item_space, window, cx)
957 };
958
959 leading_overdraw += size.height;
960 measured_items.push_front(ListItem::Measured {
961 size,
962 focus_handle: item.focus_handle(),
963 });
964 } else {
965 break;
966 }
967 }
968
969 let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
970 let mut cursor = old_items.cursor::<Count>(());
971 let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right);
972 new_items.extend(measured_items, ());
973 cursor.seek(&Count(measured_range.end), Bias::Right);
974 new_items.append(cursor.suffix(), ());
975 self.items = new_items;
976
977 // If follow_tail mode is on but the user scrolled away
978 // (is_following is false), check whether the current scroll
979 // position has returned to the bottom.
980 if self.follow_state.has_stopped_following() {
981 let padding = self.last_padding.unwrap_or_default();
982 let total_height = self.items.summary().height + padding.top + padding.bottom;
983 let scroll_offset = self.scroll_top(&scroll_top);
984 if scroll_offset + available_height >= total_height - px(1.0) {
985 self.follow_state.start_following();
986 }
987 }
988
989 // If none of the visible items are focused, check if an off-screen item is focused
990 // and include it to be rendered after the visible items so keyboard interaction continues
991 // to work for it.
992 if !rendered_focused_item {
993 let mut cursor = self
994 .items
995 .filter::<_, Count>((), |summary| summary.has_focus_handles);
996 cursor.next();
997 while let Some(item) = cursor.item() {
998 if item.contains_focused(window, cx) {
999 let item_index = cursor.start().0;
1000 let mut element = render_item(cursor.start().0, window, cx);
1001 let size = element.layout_as_root(available_item_space, window, cx);
1002 item_layouts.push_back(ItemLayout {
1003 index: item_index,
1004 element,
1005 size,
1006 });
1007 break;
1008 }
1009 cursor.next();
1010 }
1011 }
1012
1013 LayoutItemsResponse {
1014 max_item_width,
1015 scroll_top,
1016 item_layouts,
1017 }
1018 }
1019
1020 fn prepaint_items(
1021 &mut self,
1022 bounds: Bounds<Pixels>,
1023 padding: Edges<Pixels>,
1024 autoscroll: bool,
1025 render_item: &mut RenderItemFn,
1026 window: &mut Window,
1027 cx: &mut App,
1028 ) -> Result<LayoutItemsResponse, ListOffset> {
1029 window.transact(|window| {
1030 match self.measuring_behavior {
1031 ListMeasuringBehavior::Measure(has_measured) if !has_measured => {
1032 self.layout_all_items(bounds.size.width, render_item, window, cx);
1033 }
1034 _ => {}
1035 }
1036
1037 let mut layout_response = self.layout_items(
1038 Some(bounds.size.width),
1039 bounds.size.height,
1040 &padding,
1041 render_item,
1042 window,
1043 cx,
1044 );
1045
1046 // Avoid honoring autoscroll requests from elements other than our children.
1047 window.take_autoscroll();
1048
1049 // Only paint the visible items, if there is actually any space for them (taking padding into account)
1050 if bounds.size.height > padding.top + padding.bottom {
1051 let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
1052 item_origin.y -= layout_response.scroll_top.offset_in_item;
1053 for item in &mut layout_response.item_layouts {
1054 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1055 item.element.prepaint_at(item_origin, window, cx);
1056 });
1057
1058 if let Some(autoscroll_bounds) = window.take_autoscroll()
1059 && autoscroll
1060 {
1061 if autoscroll_bounds.top() < bounds.top() {
1062 return Err(ListOffset {
1063 item_ix: item.index,
1064 offset_in_item: autoscroll_bounds.top() - item_origin.y,
1065 });
1066 } else if autoscroll_bounds.bottom() > bounds.bottom() {
1067 let mut cursor = self.items.cursor::<Count>(());
1068 cursor.seek(&Count(item.index), Bias::Right);
1069 let mut height = bounds.size.height - padding.top - padding.bottom;
1070
1071 // Account for the height of the element down until the autoscroll bottom.
1072 height -= autoscroll_bounds.bottom() - item_origin.y;
1073
1074 // Keep decreasing the scroll top until we fill all the available space.
1075 while height > Pixels::ZERO {
1076 cursor.prev();
1077 let Some(item) = cursor.item() else { break };
1078
1079 let size = item.size().unwrap_or_else(|| {
1080 let mut item = render_item(cursor.start().0, window, cx);
1081 let item_available_size =
1082 size(bounds.size.width.into(), AvailableSpace::MinContent);
1083 item.layout_as_root(item_available_size, window, cx)
1084 });
1085 height -= size.height;
1086 }
1087
1088 return Err(ListOffset {
1089 item_ix: cursor.start().0,
1090 offset_in_item: if height < Pixels::ZERO {
1091 -height
1092 } else {
1093 Pixels::ZERO
1094 },
1095 });
1096 }
1097 }
1098
1099 item_origin.y += item.size.height;
1100 }
1101 } else {
1102 layout_response.item_layouts.clear();
1103 }
1104
1105 Ok(layout_response)
1106 })
1107 }
1108
1109 // Scrollbar support
1110
1111 fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
1112 let Some(bounds) = self.last_layout_bounds else {
1113 return;
1114 };
1115 let height = bounds.size.height;
1116
1117 let padding = self.last_padding.unwrap_or_default();
1118 let content_height = self.items.summary().height;
1119 let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
1120 let drag_offset =
1121 // if dragging the scrollbar, we want to offset the point if the height changed
1122 content_height - self.scrollbar_drag_start_height.unwrap_or(content_height);
1123 let new_scroll_top = (point.y - drag_offset).abs().max(px(0.)).min(scroll_max);
1124
1125 self.follow_state = FollowState::Normal;
1126
1127 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
1128 self.logical_scroll_top = None;
1129 } else {
1130 let (start, _, _) =
1131 self.items
1132 .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
1133
1134 let item_ix = start.count;
1135 let offset_in_item = new_scroll_top - start.height;
1136 self.logical_scroll_top = Some(ListOffset {
1137 item_ix,
1138 offset_in_item,
1139 });
1140 }
1141 }
1142}
1143
1144impl std::fmt::Debug for ListItem {
1145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1146 match self {
1147 Self::Unmeasured { .. } => write!(f, "Unrendered"),
1148 Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
1149 }
1150 }
1151}
1152
1153/// An offset into the list's items, in terms of the item index and the number
1154/// of pixels off the top left of the item.
1155#[derive(Debug, Clone, Copy, Default)]
1156pub struct ListOffset {
1157 /// The index of an item in the list
1158 pub item_ix: usize,
1159 /// The number of pixels to offset from the item index.
1160 pub offset_in_item: Pixels,
1161}
1162
1163impl Element for List {
1164 type RequestLayoutState = ();
1165 type PrepaintState = ListPrepaintState;
1166
1167 fn id(&self) -> Option<crate::ElementId> {
1168 None
1169 }
1170
1171 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1172 None
1173 }
1174
1175 fn request_layout(
1176 &mut self,
1177 _id: Option<&GlobalElementId>,
1178 _inspector_id: Option<&InspectorElementId>,
1179 window: &mut Window,
1180 cx: &mut App,
1181 ) -> (crate::LayoutId, Self::RequestLayoutState) {
1182 let layout_id = match self.sizing_behavior {
1183 ListSizingBehavior::Infer => {
1184 let mut style = Style::default();
1185 style.overflow.y = Overflow::Scroll;
1186 style.refine(&self.style);
1187 window.with_text_style(style.text_style().cloned(), |window| {
1188 let state = &mut *self.state.0.borrow_mut();
1189
1190 let available_height = if let Some(last_bounds) = state.last_layout_bounds {
1191 last_bounds.size.height
1192 } else {
1193 // If we don't have the last layout bounds (first render),
1194 // we might just use the overdraw value as the available height to layout enough items.
1195 state.overdraw
1196 };
1197 let padding = style.padding.to_pixels(
1198 state.last_layout_bounds.unwrap_or_default().size.into(),
1199 window.rem_size(),
1200 );
1201
1202 let layout_response = state.layout_items(
1203 None,
1204 available_height,
1205 &padding,
1206 &mut self.render_item,
1207 window,
1208 cx,
1209 );
1210 let max_element_width = layout_response.max_item_width;
1211
1212 let summary = state.items.summary();
1213 let total_height = summary.height;
1214
1215 window.request_measured_layout(
1216 style,
1217 move |known_dimensions, available_space, _window, _cx| {
1218 let width =
1219 known_dimensions
1220 .width
1221 .unwrap_or(match available_space.width {
1222 AvailableSpace::Definite(x) => x,
1223 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1224 max_element_width
1225 }
1226 });
1227 let height = match available_space.height {
1228 AvailableSpace::Definite(height) => total_height.min(height),
1229 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1230 total_height
1231 }
1232 };
1233 size(width, height)
1234 },
1235 )
1236 })
1237 }
1238 ListSizingBehavior::Auto => {
1239 let mut style = Style::default();
1240 style.refine(&self.style);
1241 window.with_text_style(style.text_style().cloned(), |window| {
1242 window.request_layout(style, None, cx)
1243 })
1244 }
1245 };
1246 (layout_id, ())
1247 }
1248
1249 fn prepaint(
1250 &mut self,
1251 _id: Option<&GlobalElementId>,
1252 _inspector_id: Option<&InspectorElementId>,
1253 bounds: Bounds<Pixels>,
1254 _: &mut Self::RequestLayoutState,
1255 window: &mut Window,
1256 cx: &mut App,
1257 ) -> ListPrepaintState {
1258 let state = &mut *self.state.0.borrow_mut();
1259 state.reset = false;
1260
1261 let mut style = Style::default();
1262 style.refine(&self.style);
1263
1264 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1265
1266 // If the width of the list has changed, invalidate all cached item heights
1267 if state
1268 .last_layout_bounds
1269 .is_none_or(|last_bounds| last_bounds.size.width != bounds.size.width)
1270 {
1271 let new_items = SumTree::from_iter(
1272 state.items.iter().map(|item| ListItem::Unmeasured {
1273 size_hint: None,
1274 focus_handle: item.focus_handle(),
1275 }),
1276 (),
1277 );
1278
1279 state.items = new_items;
1280 state.measuring_behavior.reset();
1281 }
1282
1283 let padding = style
1284 .padding
1285 .to_pixels(bounds.size.into(), window.rem_size());
1286 let layout =
1287 match state.prepaint_items(bounds, padding, true, &mut self.render_item, window, cx) {
1288 Ok(layout) => layout,
1289 Err(autoscroll_request) => {
1290 state.logical_scroll_top = Some(autoscroll_request);
1291 state
1292 .prepaint_items(bounds, padding, false, &mut self.render_item, window, cx)
1293 .unwrap()
1294 }
1295 };
1296
1297 state.last_layout_bounds = Some(bounds);
1298 state.last_padding = Some(padding);
1299 ListPrepaintState { hitbox, layout }
1300 }
1301
1302 fn paint(
1303 &mut self,
1304 _id: Option<&GlobalElementId>,
1305 _inspector_id: Option<&InspectorElementId>,
1306 bounds: Bounds<crate::Pixels>,
1307 _: &mut Self::RequestLayoutState,
1308 prepaint: &mut Self::PrepaintState,
1309 window: &mut Window,
1310 cx: &mut App,
1311 ) {
1312 let current_view = window.current_view();
1313 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1314 for item in &mut prepaint.layout.item_layouts {
1315 item.element.paint(window, cx);
1316 }
1317 });
1318
1319 let list_state = self.state.clone();
1320 let height = bounds.size.height;
1321 let scroll_top = prepaint.layout.scroll_top;
1322 let hitbox_id = prepaint.hitbox.id;
1323 let mut accumulated_scroll_delta = ScrollDelta::default();
1324 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
1325 if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
1326 accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
1327 let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1328 list_state.0.borrow_mut().scroll(
1329 &scroll_top,
1330 height,
1331 pixel_delta,
1332 current_view,
1333 window,
1334 cx,
1335 )
1336 }
1337 });
1338 }
1339}
1340
1341impl IntoElement for List {
1342 type Element = Self;
1343
1344 fn into_element(self) -> Self::Element {
1345 self
1346 }
1347}
1348
1349impl Styled for List {
1350 fn style(&mut self) -> &mut StyleRefinement {
1351 &mut self.style
1352 }
1353}
1354
1355impl sum_tree::Item for ListItem {
1356 type Summary = ListItemSummary;
1357
1358 fn summary(&self, _: ()) -> Self::Summary {
1359 match self {
1360 ListItem::Unmeasured {
1361 size_hint,
1362 focus_handle,
1363 } => ListItemSummary {
1364 count: 1,
1365 rendered_count: 0,
1366 unrendered_count: 1,
1367 height: if let Some(size) = size_hint {
1368 size.height
1369 } else {
1370 px(0.)
1371 },
1372 has_focus_handles: focus_handle.is_some(),
1373 },
1374 ListItem::Measured {
1375 size, focus_handle, ..
1376 } => ListItemSummary {
1377 count: 1,
1378 rendered_count: 1,
1379 unrendered_count: 0,
1380 height: size.height,
1381 has_focus_handles: focus_handle.is_some(),
1382 },
1383 }
1384 }
1385}
1386
1387impl sum_tree::ContextLessSummary for ListItemSummary {
1388 fn zero() -> Self {
1389 Default::default()
1390 }
1391
1392 fn add_summary(&mut self, summary: &Self) {
1393 self.count += summary.count;
1394 self.rendered_count += summary.rendered_count;
1395 self.unrendered_count += summary.unrendered_count;
1396 self.height += summary.height;
1397 self.has_focus_handles |= summary.has_focus_handles;
1398 }
1399}
1400
1401impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1402 fn zero(_cx: ()) -> Self {
1403 Default::default()
1404 }
1405
1406 fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1407 self.0 += summary.count;
1408 }
1409}
1410
1411impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1412 fn zero(_cx: ()) -> Self {
1413 Default::default()
1414 }
1415
1416 fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1417 self.0 += summary.height;
1418 }
1419}
1420
1421impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1422 fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1423 self.0.partial_cmp(&other.count).unwrap()
1424 }
1425}
1426
1427impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1428 fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1429 self.0.partial_cmp(&other.height).unwrap()
1430 }
1431}
1432
1433#[cfg(test)]
1434mod test {
1435
1436 use gpui::{ScrollDelta, ScrollWheelEvent};
1437 use std::cell::Cell;
1438 use std::rc::Rc;
1439
1440 use crate::{
1441 self as gpui, AppContext, Context, Element, FollowMode, IntoElement, ListState, Render,
1442 Styled, TestAppContext, Window, div, list, point, px, size,
1443 };
1444
1445 #[gpui::test]
1446 fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
1447 let cx = cx.add_empty_window();
1448
1449 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1450
1451 // Ensure that the list is scrolled to the top
1452 state.scroll_to(gpui::ListOffset {
1453 item_ix: 0,
1454 offset_in_item: px(0.0),
1455 });
1456
1457 struct TestView(ListState);
1458 impl Render for TestView {
1459 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1460 list(self.0.clone(), |_, _, _| {
1461 div().h(px(10.)).w_full().into_any()
1462 })
1463 .w_full()
1464 .h_full()
1465 }
1466 }
1467
1468 // Paint
1469 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1470 cx.new(|_| TestView(state.clone())).into_any_element()
1471 });
1472
1473 // Reset
1474 state.reset(5);
1475
1476 // And then receive a scroll event _before_ the next paint
1477 cx.simulate_event(ScrollWheelEvent {
1478 position: point(px(1.), px(1.)),
1479 delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
1480 ..Default::default()
1481 });
1482
1483 // Scroll position should stay at the top of the list
1484 assert_eq!(state.logical_scroll_top().item_ix, 0);
1485 assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
1486 }
1487
1488 #[gpui::test]
1489 fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
1490 let cx = cx.add_empty_window();
1491
1492 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1493
1494 struct TestView(ListState);
1495 impl Render for TestView {
1496 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1497 list(self.0.clone(), |_, _, _| {
1498 div().h(px(20.)).w_full().into_any()
1499 })
1500 .w_full()
1501 .h_full()
1502 }
1503 }
1504
1505 // Paint
1506 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1507 cx.new(|_| TestView(state.clone())).into_any_element()
1508 });
1509
1510 // Test positive distance: start at item 1, move down 30px
1511 state.scroll_by(px(30.));
1512
1513 // Should move to item 2
1514 let offset = state.logical_scroll_top();
1515 assert_eq!(offset.item_ix, 1);
1516 assert_eq!(offset.offset_in_item, px(10.));
1517
1518 // Test negative distance: start at item 2, move up 30px
1519 state.scroll_by(px(-30.));
1520
1521 // Should move back to item 1
1522 let offset = state.logical_scroll_top();
1523 assert_eq!(offset.item_ix, 0);
1524 assert_eq!(offset.offset_in_item, px(0.));
1525
1526 // Test zero distance
1527 state.scroll_by(px(0.));
1528 let offset = state.logical_scroll_top();
1529 assert_eq!(offset.item_ix, 0);
1530 assert_eq!(offset.offset_in_item, px(0.));
1531 }
1532
1533 #[gpui::test]
1534 fn test_measure_all_after_width_change(cx: &mut TestAppContext) {
1535 let cx = cx.add_empty_window();
1536
1537 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
1538
1539 struct TestView(ListState);
1540 impl Render for TestView {
1541 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1542 list(self.0.clone(), |_, _, _| {
1543 div().h(px(50.)).w_full().into_any()
1544 })
1545 .w_full()
1546 .h_full()
1547 }
1548 }
1549
1550 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1551
1552 // First draw at width 100: all 10 items measured (total 500px).
1553 // Viewport is 200px, so max scroll offset should be 300px.
1554 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1555 view.clone().into_any_element()
1556 });
1557 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
1558
1559 // Second draw at a different width: items get invalidated.
1560 // Without the fix, max_offset would drop because unmeasured items
1561 // contribute 0 height.
1562 cx.draw(point(px(0.), px(0.)), size(px(200.), px(200.)), |_, _| {
1563 view.into_any_element()
1564 });
1565 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
1566 }
1567
1568 #[gpui::test]
1569 fn test_remeasure(cx: &mut TestAppContext) {
1570 let cx = cx.add_empty_window();
1571
1572 // Create a list with 10 items, each 100px tall. We'll keep a reference
1573 // to the item height so we can later change the height and assert how
1574 // `ListState` handles it.
1575 let item_height = Rc::new(Cell::new(100usize));
1576 let state = ListState::new(10, crate::ListAlignment::Top, px(10.));
1577
1578 struct TestView {
1579 state: ListState,
1580 item_height: Rc<Cell<usize>>,
1581 }
1582
1583 impl Render for TestView {
1584 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1585 let height = self.item_height.get();
1586 list(self.state.clone(), move |_, _, _| {
1587 div().h(px(height as f32)).w_full().into_any()
1588 })
1589 .w_full()
1590 .h_full()
1591 }
1592 }
1593
1594 let state_clone = state.clone();
1595 let item_height_clone = item_height.clone();
1596 let view = cx.update(|_, cx| {
1597 cx.new(|_| TestView {
1598 state: state_clone,
1599 item_height: item_height_clone,
1600 })
1601 });
1602
1603 // Simulate scrolling 40px inside the element with index 2. Since the
1604 // original item height is 100px, this equates to 40% inside the item.
1605 state.scroll_to(gpui::ListOffset {
1606 item_ix: 2,
1607 offset_in_item: px(40.),
1608 });
1609
1610 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1611 view.clone().into_any_element()
1612 });
1613
1614 let offset = state.logical_scroll_top();
1615 assert_eq!(offset.item_ix, 2);
1616 assert_eq!(offset.offset_in_item, px(40.));
1617
1618 // Update the `item_height` to be 50px instead of 100px so we can assert
1619 // that the scroll position is proportionally preserved, that is,
1620 // instead of 40px from the top of item 2, it should be 20px, since the
1621 // item's height has been halved.
1622 item_height.set(50);
1623 state.remeasure();
1624
1625 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1626 view.into_any_element()
1627 });
1628
1629 let offset = state.logical_scroll_top();
1630 assert_eq!(offset.item_ix, 2);
1631 assert_eq!(offset.offset_in_item, px(20.));
1632 }
1633
1634 #[gpui::test]
1635 fn test_follow_tail_stays_at_bottom_as_items_grow(cx: &mut TestAppContext) {
1636 let cx = cx.add_empty_window();
1637
1638 // 10 items, each 50px tall β 500px total content, 200px viewport.
1639 // With follow-tail on, the list should always show the bottom.
1640 let item_height = Rc::new(Cell::new(50usize));
1641 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
1642
1643 struct TestView {
1644 state: ListState,
1645 item_height: Rc<Cell<usize>>,
1646 }
1647 impl Render for TestView {
1648 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1649 let height = self.item_height.get();
1650 list(self.state.clone(), move |_, _, _| {
1651 div().h(px(height as f32)).w_full().into_any()
1652 })
1653 .w_full()
1654 .h_full()
1655 }
1656 }
1657
1658 let state_clone = state.clone();
1659 let item_height_clone = item_height.clone();
1660 let view = cx.update(|_, cx| {
1661 cx.new(|_| TestView {
1662 state: state_clone,
1663 item_height: item_height_clone,
1664 })
1665 });
1666
1667 state.set_follow_mode(FollowMode::Tail);
1668
1669 // First paint β items are 50px, total 500px, viewport 200px.
1670 // Follow-tail should anchor to the end.
1671 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1672 view.clone().into_any_element()
1673 });
1674
1675 // The scroll should be at the bottom: the last visible items fill the
1676 // 200px viewport from the end of 500px of content (offset 300px).
1677 let offset = state.logical_scroll_top();
1678 assert_eq!(offset.item_ix, 6);
1679 assert_eq!(offset.offset_in_item, px(0.));
1680 assert!(state.is_following_tail());
1681
1682 // Simulate items growing (e.g. streaming content makes each item taller).
1683 // 10 items Γ 80px = 800px total.
1684 item_height.set(80);
1685 state.remeasure();
1686
1687 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1688 view.into_any_element()
1689 });
1690
1691 // After growth, follow-tail should have re-anchored to the new end.
1692 // 800px total β 200px viewport = 600px offset β item 7 at offset 40px,
1693 // but follow-tail anchors to item_count (10), and layout walks back to
1694 // fill 200px, landing at item 7 (7 Γ 80 = 560, 800 β 560 = 240 > 200,
1695 // so item 8: 8 Γ 80 = 640, 800 β 640 = 160 < 200 β keeps walking β
1696 // item 7: offset = 800 β 200 = 600, item_ix = 600/80 = 7, remainder 40).
1697 let offset = state.logical_scroll_top();
1698 assert_eq!(offset.item_ix, 7);
1699 assert_eq!(offset.offset_in_item, px(40.));
1700 assert!(state.is_following_tail());
1701 }
1702
1703 #[gpui::test]
1704 fn test_follow_tail_disengages_on_user_scroll(cx: &mut TestAppContext) {
1705 let cx = cx.add_empty_window();
1706
1707 // 10 items Γ 50px = 500px total, 200px viewport.
1708 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
1709
1710 struct TestView(ListState);
1711 impl Render for TestView {
1712 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1713 list(self.0.clone(), |_, _, _| {
1714 div().h(px(50.)).w_full().into_any()
1715 })
1716 .w_full()
1717 .h_full()
1718 }
1719 }
1720
1721 state.set_follow_mode(FollowMode::Tail);
1722
1723 // Paint with follow-tail β scroll anchored to the bottom.
1724 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, cx| {
1725 cx.new(|_| TestView(state.clone())).into_any_element()
1726 });
1727 assert!(state.is_following_tail());
1728
1729 // Simulate the user scrolling up.
1730 // This should disengage follow-tail.
1731 cx.simulate_event(ScrollWheelEvent {
1732 position: point(px(50.), px(100.)),
1733 delta: ScrollDelta::Pixels(point(px(0.), px(100.))),
1734 ..Default::default()
1735 });
1736
1737 assert!(
1738 !state.is_following_tail(),
1739 "follow-tail should disengage when the user scrolls toward the start"
1740 );
1741 }
1742
1743 #[gpui::test]
1744 fn test_follow_tail_disengages_on_scrollbar_reposition(cx: &mut TestAppContext) {
1745 let cx = cx.add_empty_window();
1746
1747 // 10 items Γ 50px = 500px total, 200px viewport.
1748 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
1749
1750 struct TestView(ListState);
1751 impl Render for TestView {
1752 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1753 list(self.0.clone(), |_, _, _| {
1754 div().h(px(50.)).w_full().into_any()
1755 })
1756 .w_full()
1757 .h_full()
1758 }
1759 }
1760
1761 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1762
1763 state.set_follow_mode(FollowMode::Tail);
1764
1765 // Paint with follow-tail β scroll anchored to the bottom.
1766 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1767 view.clone().into_any_element()
1768 });
1769 assert!(state.is_following_tail());
1770
1771 // Simulate the scrollbar moving the viewport to the middle.
1772 // `set_offset_from_scrollbar` accepts a positive distance from the start.
1773 state.set_offset_from_scrollbar(point(px(0.), px(150.)));
1774
1775 let offset = state.logical_scroll_top();
1776 assert_eq!(offset.item_ix, 3);
1777 assert_eq!(offset.offset_in_item, px(0.));
1778 assert!(
1779 !state.is_following_tail(),
1780 "follow-tail should disengage when the scrollbar manually repositions the list"
1781 );
1782
1783 // A subsequent draw should preserve the user's manual position instead
1784 // of snapping back to the end.
1785 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1786 view.into_any_element()
1787 });
1788
1789 let offset = state.logical_scroll_top();
1790 assert_eq!(offset.item_ix, 3);
1791 assert_eq!(offset.offset_in_item, px(0.));
1792 }
1793
1794 #[gpui::test]
1795 fn test_set_follow_tail_snaps_to_bottom(cx: &mut TestAppContext) {
1796 let cx = cx.add_empty_window();
1797
1798 // 10 items Γ 50px = 500px total, 200px viewport.
1799 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
1800
1801 struct TestView(ListState);
1802 impl Render for TestView {
1803 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1804 list(self.0.clone(), |_, _, _| {
1805 div().h(px(50.)).w_full().into_any()
1806 })
1807 .w_full()
1808 .h_full()
1809 }
1810 }
1811
1812 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1813
1814 // Scroll to the middle of the list (item 3).
1815 state.scroll_to(gpui::ListOffset {
1816 item_ix: 3,
1817 offset_in_item: px(0.),
1818 });
1819
1820 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1821 view.clone().into_any_element()
1822 });
1823
1824 let offset = state.logical_scroll_top();
1825 assert_eq!(offset.item_ix, 3);
1826 assert_eq!(offset.offset_in_item, px(0.));
1827 assert!(!state.is_following_tail());
1828
1829 // Enable follow-tail β this should immediately snap the scroll anchor
1830 // to the end, like the user just sent a prompt.
1831 state.set_follow_mode(FollowMode::Tail);
1832
1833 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1834 view.into_any_element()
1835 });
1836
1837 // After paint, scroll should be at the bottom.
1838 // 500px total β 200px viewport = 300px offset β item 6, offset 0.
1839 let offset = state.logical_scroll_top();
1840 assert_eq!(offset.item_ix, 6);
1841 assert_eq!(offset.offset_in_item, px(0.));
1842 assert!(state.is_following_tail());
1843 }
1844
1845 #[gpui::test]
1846 fn test_bottom_aligned_scrollbar_offset_at_end(cx: &mut TestAppContext) {
1847 let cx = cx.add_empty_window();
1848
1849 const ITEMS: usize = 10;
1850 const ITEM_SIZE: f32 = 50.0;
1851
1852 let state = ListState::new(
1853 ITEMS,
1854 crate::ListAlignment::Bottom,
1855 px(ITEMS as f32 * ITEM_SIZE),
1856 );
1857
1858 struct TestView(ListState);
1859 impl Render for TestView {
1860 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1861 list(self.0.clone(), |_, _, _| {
1862 div().h(px(ITEM_SIZE)).w_full().into_any()
1863 })
1864 .w_full()
1865 .h_full()
1866 }
1867 }
1868
1869 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1870 cx.new(|_| TestView(state.clone())).into_any_element()
1871 });
1872
1873 // Bottom-aligned lists start pinned to the end: logical_scroll_top returns
1874 // item_ix == item_count, meaning no explicit scroll position has been set.
1875 assert_eq!(state.logical_scroll_top().item_ix, ITEMS);
1876
1877 let max_offset = state.max_offset_for_scrollbar();
1878 let scroll_offset = state.scroll_px_offset_for_scrollbar();
1879
1880 assert_eq!(
1881 -scroll_offset.y, max_offset.y,
1882 "scrollbar offset ({}) should equal max offset ({}) when list is pinned to bottom",
1883 -scroll_offset.y, max_offset.y,
1884 );
1885 }
1886
1887 /// When the user scrolls away from the bottom during follow_tail,
1888 /// follow_tail suspends. If they scroll back to the bottom, the
1889 /// next paint should re-engage follow_tail using fresh measurements.
1890 #[gpui::test]
1891 fn test_follow_tail_reengages_when_scrolled_back_to_bottom(cx: &mut TestAppContext) {
1892 let cx = cx.add_empty_window();
1893
1894 // 10 items Γ 50px = 500px total, 200px viewport.
1895 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
1896
1897 struct TestView(ListState);
1898 impl Render for TestView {
1899 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1900 list(self.0.clone(), |_, _, _| {
1901 div().h(px(50.)).w_full().into_any()
1902 })
1903 .w_full()
1904 .h_full()
1905 }
1906 }
1907
1908 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1909
1910 state.set_follow_mode(FollowMode::Tail);
1911
1912 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1913 view.clone().into_any_element()
1914 });
1915 assert!(state.is_following_tail());
1916
1917 // Scroll up β follow_tail should suspend (not fully disengage).
1918 cx.simulate_event(ScrollWheelEvent {
1919 position: point(px(50.), px(100.)),
1920 delta: ScrollDelta::Pixels(point(px(0.), px(50.))),
1921 ..Default::default()
1922 });
1923 assert!(!state.is_following_tail());
1924
1925 // Scroll back down to the bottom.
1926 cx.simulate_event(ScrollWheelEvent {
1927 position: point(px(50.), px(100.)),
1928 delta: ScrollDelta::Pixels(point(px(0.), px(-10000.))),
1929 ..Default::default()
1930 });
1931
1932 // After a paint, follow_tail should re-engage because the
1933 // layout confirmed we're at the true bottom.
1934 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1935 view.clone().into_any_element()
1936 });
1937 assert!(
1938 state.is_following_tail(),
1939 "follow_tail should re-engage after scrolling back to the bottom"
1940 );
1941 }
1942
1943 /// When an item is spliced to unmeasured (0px) while follow_tail
1944 /// is suspended, the re-engagement check should still work correctly
1945 #[gpui::test]
1946 fn test_follow_tail_reengagement_not_fooled_by_unmeasured_items(cx: &mut TestAppContext) {
1947 let cx = cx.add_empty_window();
1948
1949 // 20 items Γ 50px = 1000px total, 200px viewport, 1000px
1950 // overdraw so all items get measured during the follow_tail
1951 // paint (matching realistic production settings).
1952 let state = ListState::new(20, crate::ListAlignment::Top, px(1000.));
1953
1954 struct TestView(ListState);
1955 impl Render for TestView {
1956 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1957 list(self.0.clone(), |_, _, _| {
1958 div().h(px(50.)).w_full().into_any()
1959 })
1960 .w_full()
1961 .h_full()
1962 }
1963 }
1964
1965 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
1966
1967 state.set_follow_mode(FollowMode::Tail);
1968
1969 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1970 view.clone().into_any_element()
1971 });
1972 assert!(state.is_following_tail());
1973
1974 // Scroll up a meaningful amount β suspends follow_tail.
1975 // 20 items Γ 50px = 1000px. viewport 200px. scroll_max = 800px.
1976 // Scrolling up 200px puts us at 600px, clearly not at bottom.
1977 cx.simulate_event(ScrollWheelEvent {
1978 position: point(px(50.), px(100.)),
1979 delta: ScrollDelta::Pixels(point(px(0.), px(200.))),
1980 ..Default::default()
1981 });
1982 assert!(!state.is_following_tail());
1983
1984 // Invalidate the last item (simulates EntryUpdated calling
1985 // remeasure_items). This makes items.summary().height
1986 // temporarily wrong (0px for the invalidated item).
1987 state.remeasure_items(19..20);
1988
1989 // Paint β layout re-measures the invalidated item with its true
1990 // height. The re-engagement check uses these fresh measurements.
1991 // Since we scrolled 200px up from the 800px max, we're at
1992 // ~600px β NOT at the bottom, so follow_tail should NOT
1993 // re-engage.
1994 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
1995 view.clone().into_any_element()
1996 });
1997 assert!(
1998 !state.is_following_tail(),
1999 "follow_tail should not falsely re-engage due to an unmeasured item \
2000 reducing items.summary().height"
2001 );
2002 }
2003
2004 /// Calling `set_follow_mode(FollowState::Normal)` or dragging the scrollbar should
2005 /// fully disengage follow_tail β clearing any suspended state so
2006 /// follow_tail wonβt auto-re-engage.
2007 #[gpui::test]
2008 fn test_follow_tail_suspended_state_cleared_by_explicit_actions(cx: &mut TestAppContext) {
2009 let cx = cx.add_empty_window();
2010
2011 // 10 items Γ 50px = 500px total, 200px viewport.
2012 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2013
2014 struct TestView(ListState);
2015 impl Render for TestView {
2016 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2017 list(self.0.clone(), |_, _, _| {
2018 div().h(px(50.)).w_full().into_any()
2019 })
2020 .w_full()
2021 .h_full()
2022 }
2023 }
2024
2025 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2026
2027 state.set_follow_mode(FollowMode::Tail);
2028 // --- Part 1: set_follow_mode(FollowState::Normal) clears suspended state ---
2029
2030 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2031 view.clone().into_any_element()
2032 });
2033
2034 // Scroll up β suspends follow_tail.
2035 cx.simulate_event(ScrollWheelEvent {
2036 position: point(px(50.), px(100.)),
2037 delta: ScrollDelta::Pixels(point(px(0.), px(50.))),
2038 ..Default::default()
2039 });
2040 assert!(!state.is_following_tail());
2041
2042 // Scroll back to the bottom β should re-engage follow_tail.
2043 cx.simulate_event(ScrollWheelEvent {
2044 position: point(px(50.), px(100.)),
2045 delta: ScrollDelta::Pixels(point(px(0.), px(-10000.))),
2046 ..Default::default()
2047 });
2048
2049 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2050 view.clone().into_any_element()
2051 });
2052 assert!(
2053 state.is_following_tail(),
2054 "follow_tail should re-engage after scrolling back to the bottom"
2055 );
2056
2057 // --- Part 2: scrollbar drag clears suspended state ---
2058
2059 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2060 view.clone().into_any_element()
2061 });
2062
2063 // Drag the scrollbar to the middle β should clear suspended state.
2064 state.set_offset_from_scrollbar(point(px(0.), px(150.)));
2065
2066 // Scroll to the bottom.
2067 cx.simulate_event(ScrollWheelEvent {
2068 position: point(px(50.), px(100.)),
2069 delta: ScrollDelta::Pixels(point(px(0.), px(-10000.))),
2070 ..Default::default()
2071 });
2072
2073 // Paint β should NOT re-engage because the scrollbar drag
2074 // cleared the suspended state.
2075 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2076 view.clone().into_any_element()
2077 });
2078 assert!(
2079 !state.is_following_tail(),
2080 "follow_tail should not re-engage after scrollbar drag cleared the suspended state"
2081 );
2082 }
2083}