1use crate::{
11 AnyElement, App, AvailableSpace, Bounds, ContentMask, DispatchPhase, Edges, Element, EntityId,
12 FocusHandle, GlobalElementId, Hitbox, HitboxBehavior, IntoElement, Overflow, Pixels, Point,
13 ScrollDelta, ScrollWheelEvent, Size, Style, StyleRefinement, Styled, Window, point, px, size,
14};
15use collections::VecDeque;
16use refineable::Refineable as _;
17use std::{cell::RefCell, ops::Range, rc::Rc};
18use sum_tree::{Bias, Dimensions, SumTree};
19
20type RenderItemFn = dyn FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static;
21
22pub fn list(
24 state: ListState,
25 render_item: impl FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static,
26) -> List {
27 List {
28 state,
29 render_item: Box::new(render_item),
30 style: StyleRefinement::default(),
31 sizing_behavior: ListSizingBehavior::default(),
32 }
33}
34
35pub struct List {
37 state: ListState,
38 render_item: Box<RenderItemFn>,
39 style: StyleRefinement,
40 sizing_behavior: ListSizingBehavior,
41}
42
43impl List {
44 pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
46 self.sizing_behavior = behavior;
47 self
48 }
49}
50
51#[derive(Clone)]
53pub struct ListState(Rc<RefCell<StateInner>>);
54
55impl std::fmt::Debug for ListState {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 f.write_str("ListState")
58 }
59}
60
61struct StateInner {
62 last_layout_bounds: Option<Bounds<Pixels>>,
63 last_padding: Option<Edges<Pixels>>,
64 items: SumTree<ListItem>,
65 logical_scroll_top: Option<ListOffset>,
66 alignment: ListAlignment,
67 overdraw: Pixels,
68 reset: bool,
69 #[allow(clippy::type_complexity)]
70 scroll_handler: Option<Box<dyn FnMut(&ListScrollEvent, &mut Window, &mut App)>>,
71 scrollbar_drag_start_height: Option<Pixels>,
72 measuring_behavior: ListMeasuringBehavior,
73 pending_scroll: Option<PendingScroll>,
74 follow_state: FollowState,
75}
76
77#[derive(Clone)]
84enum PendingScroll {
85 Absolute { item_ix: usize, offset: Pixels },
87 Proportional(PendingScrollFraction),
89}
90
91#[derive(Clone)]
94struct PendingScrollFraction {
95 item_ix: usize,
97 fraction: f32,
99}
100
101enum ScrollAnchor {
104 Absolute,
106 Proportional,
108}
109
110#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
112pub enum FollowMode {
113 #[default]
115 Normal,
116 Tail,
118}
119
120#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
121enum FollowState {
122 #[default]
123 Normal,
124 Tail {
125 is_following: bool,
126 },
127}
128
129impl FollowState {
130 fn is_following(&self) -> bool {
131 matches!(self, FollowState::Tail { is_following: true })
132 }
133
134 fn has_stopped_following(&self) -> bool {
135 matches!(
136 self,
137 FollowState::Tail {
138 is_following: false
139 }
140 )
141 }
142
143 fn start_following(&mut self) {
144 if let FollowState::Tail {
145 is_following: false,
146 } = self
147 {
148 *self = FollowState::Tail { is_following: true };
149 }
150 }
151
152 fn stop_following(&mut self) {
153 if let FollowState::Tail { is_following: true } = self {
154 *self = FollowState::Tail {
155 is_following: false,
156 };
157 }
158 }
159}
160
161#[derive(Clone, Copy, Debug, Eq, PartialEq)]
163pub enum ListAlignment {
164 Top,
166 Bottom,
168}
169
170pub struct ListScrollEvent {
172 pub visible_range: Range<usize>,
174
175 pub count: usize,
177
178 pub is_scrolled: bool,
180
181 pub is_following_tail: bool,
183}
184
185#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
187pub enum ListSizingBehavior {
188 Infer,
190 #[default]
192 Auto,
193}
194
195#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
197pub enum ListMeasuringBehavior {
198 Measure(bool),
201 #[default]
203 Visible,
204}
205
206impl ListMeasuringBehavior {
207 fn reset(&mut self) {
208 match self {
209 ListMeasuringBehavior::Measure(has_measured) => *has_measured = false,
210 ListMeasuringBehavior::Visible => {}
211 }
212 }
213}
214
215#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
217pub enum ListHorizontalSizingBehavior {
218 #[default]
220 FitList,
221 Unconstrained,
223}
224
225struct LayoutItemsResponse {
226 max_item_width: Pixels,
227 scroll_top: ListOffset,
228 item_layouts: VecDeque<ItemLayout>,
229}
230
231struct ItemLayout {
232 index: usize,
233 element: AnyElement,
234 size: Size<Pixels>,
235}
236
237pub struct ListPrepaintState {
239 hitbox: Hitbox,
240 layout: LayoutItemsResponse,
241}
242
243#[derive(Clone)]
244enum ListItem {
245 Unmeasured {
246 size_hint: Option<Size<Pixels>>,
247 focus_handle: Option<FocusHandle>,
248 },
249 Measured {
250 size: Size<Pixels>,
251 focus_handle: Option<FocusHandle>,
252 },
253}
254
255impl ListItem {
256 fn size(&self) -> Option<Size<Pixels>> {
257 if let ListItem::Measured { size, .. } = self {
258 Some(*size)
259 } else {
260 None
261 }
262 }
263
264 fn size_hint(&self) -> Option<Size<Pixels>> {
265 match self {
266 ListItem::Measured { size, .. } => Some(*size),
267 ListItem::Unmeasured { size_hint, .. } => *size_hint,
268 }
269 }
270
271 fn focus_handle(&self) -> Option<FocusHandle> {
272 match self {
273 ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
274 focus_handle.clone()
275 }
276 }
277 }
278
279 fn contains_focused(&self, window: &Window, cx: &App) -> bool {
280 match self {
281 ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
282 focus_handle
283 .as_ref()
284 .is_some_and(|handle| handle.contains_focused(window, cx))
285 }
286 }
287 }
288}
289
290#[derive(Clone, Debug, Default, PartialEq)]
291struct ListItemSummary {
292 count: usize,
293 rendered_count: usize,
294 unrendered_count: usize,
295 height: Pixels,
296 has_focus_handles: bool,
297 has_unknown_height: bool,
298}
299
300#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
301struct Count(usize);
302
303#[derive(Clone, Debug, Default)]
304struct Height(Pixels);
305
306impl ListState {
307 pub fn new(item_count: usize, alignment: ListAlignment, overdraw: Pixels) -> Self {
314 let this = Self(Rc::new(RefCell::new(StateInner {
315 last_layout_bounds: None,
316 last_padding: None,
317 items: SumTree::default(),
318 logical_scroll_top: None,
319 alignment,
320 overdraw,
321 scroll_handler: None,
322 reset: false,
323 scrollbar_drag_start_height: None,
324 measuring_behavior: ListMeasuringBehavior::default(),
325 pending_scroll: None,
326 follow_state: FollowState::default(),
327 })));
328 this.splice(0..0, item_count);
329 this
330 }
331
332 pub fn measure_all(self) -> Self {
336 self.0.borrow_mut().measuring_behavior = ListMeasuringBehavior::Measure(false);
337 self
338 }
339
340 pub fn with_uniform_item_height(self, height: Pixels) -> Self {
347 self.apply_uniform_item_height(height);
348 self
349 }
350
351 pub fn reset(&self, element_count: usize) {
355 let old_count = {
356 let state = &mut *self.0.borrow_mut();
357 state.reset = true;
358 state.measuring_behavior.reset();
359 state.logical_scroll_top = None;
360 state.pending_scroll = None;
361 state.scrollbar_drag_start_height = None;
362 state.items.summary().count
363 };
364
365 self.splice(0..old_count, element_count);
366 }
367
368 pub fn reset_with_uniform_height(&self, element_count: usize, height: Pixels) {
372 self.reset(element_count);
373 self.apply_uniform_item_height(height);
374 }
375
376 fn apply_uniform_item_height(&self, height: Pixels) {
377 let size_hint = Size {
378 width: px(0.),
379 height,
380 };
381 let mut state = self.0.borrow_mut();
382 let new_items = state
383 .items
384 .iter()
385 .map(|item| ListItem::Unmeasured {
386 size_hint: Some(item.size_hint().unwrap_or(size_hint)),
387 focus_handle: item.focus_handle(),
388 })
389 .collect::<Vec<_>>();
390 let mut tree = SumTree::default();
391 tree.extend(new_items, ());
392 state.items = tree;
393 }
394
395 pub fn remeasure(&self) {
400 let count = self.item_count();
401 self.remeasure_items_with_scroll_anchor(0..count, ScrollAnchor::Proportional);
402 }
403
404 pub fn remeasure_items(&self, range: Range<usize>) {
412 self.remeasure_items_with_scroll_anchor(range, ScrollAnchor::Absolute);
413 }
414
415 fn remeasure_items_with_scroll_anchor(&self, range: Range<usize>, scroll_anchor: ScrollAnchor) {
416 let state = &mut *self.0.borrow_mut();
417
418 if let Some(scroll_top) = state.logical_scroll_top {
419 if range.contains(&scroll_top.item_ix) {
420 state.pending_scroll = match scroll_anchor {
421 ScrollAnchor::Absolute => Some(PendingScroll::Absolute {
422 item_ix: scroll_top.item_ix,
423 offset: scroll_top.offset_in_item,
424 }),
425 ScrollAnchor::Proportional => {
426 let mut cursor = state.items.cursor::<Count>(());
431 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
432
433 cursor
434 .item()
435 .and_then(|item| {
436 item.size().map(|size| {
437 let fraction = if size.height.0 > 0.0 {
438 (scroll_top.offset_in_item.0 / size.height.0)
439 .clamp(0.0, 1.0)
440 } else {
441 0.0
442 };
443
444 PendingScroll::Proportional(PendingScrollFraction {
445 item_ix: scroll_top.item_ix,
446 fraction,
447 })
448 })
449 })
450 .or_else(|| state.pending_scroll.clone())
451 }
452 };
453 }
454 }
455
456 let new_items = {
459 let mut cursor = state.items.cursor::<Count>(());
460 let mut new_items = cursor.slice(&Count(range.start), Bias::Right);
461 let invalidated = cursor.slice(&Count(range.end), Bias::Right);
462 new_items.extend(
463 invalidated.iter().map(|item| ListItem::Unmeasured {
464 size_hint: item.size_hint(),
465 focus_handle: item.focus_handle(),
466 }),
467 (),
468 );
469 new_items.append(cursor.suffix(), ());
470 new_items
471 };
472 state.items = new_items;
473 state.measuring_behavior.reset();
474 }
475
476 pub fn item_count(&self) -> usize {
478 self.0.borrow().items.summary().count
479 }
480
481 pub fn is_scrolled_to_end(&self) -> Option<bool> {
484 let state = self.0.borrow();
485 let bounds = state.last_layout_bounds?;
486 let summary = state.items.summary();
487 if summary.has_unknown_height {
488 return None;
489 }
490 let padding = state.last_padding.unwrap_or_default();
491 let content_height = summary.height + padding.top + padding.bottom;
492 let scroll_max = (content_height - bounds.size.height).max(px(0.));
493 if scroll_max <= px(0.) {
494 return None;
495 }
496 let scroll_top = state.scroll_top(&state.logical_scroll_top());
497 Some(scroll_top >= scroll_max)
498 }
499
500 pub fn splice(&self, old_range: Range<usize>, count: usize) {
503 self.splice_focusable(old_range, (0..count).map(|_| None))
504 }
505
506 pub fn splice_focusable(
511 &self,
512 old_range: Range<usize>,
513 focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
514 ) {
515 let state = &mut *self.0.borrow_mut();
516
517 let mut old_items = state.items.cursor::<Count>(());
518 let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right);
519 old_items.seek_forward(&Count(old_range.end), Bias::Right);
520
521 let mut spliced_count = 0;
522 new_items.extend(
523 focus_handles.into_iter().map(|focus_handle| {
524 spliced_count += 1;
525 ListItem::Unmeasured {
526 size_hint: None,
527 focus_handle,
528 }
529 }),
530 (),
531 );
532 new_items.append(old_items.suffix(), ());
533 drop(old_items);
534 state.items = new_items;
535
536 if let Some(ListOffset {
537 item_ix,
538 offset_in_item,
539 }) = state.logical_scroll_top.as_mut()
540 {
541 if old_range.contains(item_ix) {
542 *item_ix = old_range.start;
543 *offset_in_item = px(0.);
544 } else if old_range.end <= *item_ix {
545 *item_ix = *item_ix - (old_range.end - old_range.start) + spliced_count;
546 }
547 }
548 }
549
550 pub fn set_scroll_handler(
552 &self,
553 handler: impl FnMut(&ListScrollEvent, &mut Window, &mut App) + 'static,
554 ) {
555 self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
556 }
557
558 pub fn logical_scroll_top(&self) -> ListOffset {
560 self.0.borrow().logical_scroll_top()
561 }
562
563 pub fn scroll_by(&self, distance: Pixels) {
565 if distance == px(0.) {
566 return;
567 }
568
569 let current_offset = self.logical_scroll_top();
570 let state = &mut *self.0.borrow_mut();
571
572 if distance < px(0.) {
573 state.follow_state.stop_following();
574 }
575
576 let mut cursor = state.items.cursor::<ListItemSummary>(());
577 cursor.seek(&Count(current_offset.item_ix), Bias::Right);
578
579 let start_pixel_offset = cursor.start().height + current_offset.offset_in_item;
580 let new_pixel_offset = (start_pixel_offset + distance).max(px(0.));
581 if new_pixel_offset > start_pixel_offset {
582 cursor.seek_forward(&Height(new_pixel_offset), Bias::Right);
583 } else {
584 cursor.seek(&Height(new_pixel_offset), Bias::Right);
585 }
586
587 let scroll_top = ListOffset {
588 item_ix: cursor.start().count,
589 offset_in_item: new_pixel_offset - cursor.start().height,
590 };
591 drop(cursor);
592 state.rebase_pending_scroll(scroll_top);
593 state.logical_scroll_top = Some(scroll_top);
594 }
595
596 pub fn scroll_to_end(&self) {
603 let state = &mut *self.0.borrow_mut();
604 let item_count = state.items.summary().count;
605 state.pending_scroll = None;
606 state.logical_scroll_top = Some(ListOffset {
607 item_ix: item_count,
608 offset_in_item: px(0.),
609 });
610 }
611
612 pub fn set_follow_mode(&self, mode: FollowMode) {
617 let state = &mut *self.0.borrow_mut();
618
619 match mode {
620 FollowMode::Normal => {
621 state.follow_state = FollowState::Normal;
622 }
623 FollowMode::Tail => {
624 state.follow_state = FollowState::Tail { is_following: true };
625 if matches!(mode, FollowMode::Tail) {
626 let item_count = state.items.summary().count;
627 state.logical_scroll_top = Some(ListOffset {
628 item_ix: item_count,
629 offset_in_item: px(0.),
630 });
631 }
632 }
633 }
634 }
635
636 pub fn pause_following_tail(&self) {
646 self.0.borrow_mut().follow_state.stop_following();
647 }
648
649 pub fn is_following_tail(&self) -> bool {
652 matches!(
653 self.0.borrow().follow_state,
654 FollowState::Tail { is_following: true }
655 )
656 }
657
658 pub fn scroll_to(&self, mut scroll_top: ListOffset) {
660 let state = &mut *self.0.borrow_mut();
661 let item_count = state.items.summary().count;
662 if scroll_top.item_ix >= item_count {
663 scroll_top.item_ix = item_count;
664 scroll_top.offset_in_item = px(0.);
665 }
666
667 if scroll_top.item_ix < item_count {
668 state.follow_state.stop_following();
669 }
670
671 state.rebase_pending_scroll(scroll_top);
672 state.logical_scroll_top = Some(scroll_top);
673 }
674
675 pub fn scroll_to_reveal_item(&self, ix: usize) {
677 let state = &mut *self.0.borrow_mut();
678
679 let mut scroll_top = state.logical_scroll_top();
680 let height = state
681 .last_layout_bounds
682 .map_or(px(0.), |bounds| bounds.size.height);
683 let padding = state.last_padding.unwrap_or_default();
684
685 if ix <= scroll_top.item_ix {
686 scroll_top.item_ix = ix;
687 scroll_top.offset_in_item = px(0.);
688 } else {
689 let mut cursor = state.items.cursor::<ListItemSummary>(());
690 cursor.seek(&Count(ix + 1), Bias::Right);
691 let bottom = cursor.start().height + padding.top;
692 let goal_top = px(0.).max(bottom - height + padding.bottom);
693
694 cursor.seek(&Height(goal_top), Bias::Left);
695 let start_ix = cursor.start().count;
696 let start_item_top = cursor.start().height;
697
698 if start_ix >= scroll_top.item_ix {
699 scroll_top.item_ix = start_ix;
700 scroll_top.offset_in_item = goal_top - start_item_top;
701 }
702 }
703
704 state.rebase_pending_scroll(scroll_top);
705 state.logical_scroll_top = Some(scroll_top);
706 }
707
708 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
711 let state = &*self.0.borrow();
712
713 let bounds = state.last_layout_bounds.unwrap_or_default();
714 let scroll_top = state.logical_scroll_top();
715 if ix < scroll_top.item_ix {
716 return None;
717 }
718
719 let mut cursor = state.items.cursor::<Dimensions<Count, Height>>(());
720 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
721
722 let scroll_top = cursor.start().1.0 + scroll_top.offset_in_item;
723
724 cursor.seek_forward(&Count(ix), Bias::Right);
725 if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
726 let &Dimensions(Count(count), Height(top), _) = cursor.start();
727 if count == ix {
728 let top = bounds.top() + top - scroll_top;
729 return Some(Bounds::from_corners(
730 point(bounds.left(), top),
731 point(bounds.right(), top + size.height),
732 ));
733 }
734 }
735 None
736 }
737
738 pub fn scrollbar_drag_started(&self) {
743 let mut state = self.0.borrow_mut();
744 state.scrollbar_drag_start_height = Some(state.items.summary().height);
745 }
746
747 pub fn scrollbar_drag_ended(&self) {
751 self.0.borrow_mut().scrollbar_drag_start_height.take();
752 }
753
754 pub fn is_scrollbar_dragging(&self) -> bool {
761 self.0.borrow().scrollbar_drag_start_height.is_some()
762 }
763
764 pub fn set_offset_from_scrollbar(&self, point: Point<Pixels>) {
766 self.0.borrow_mut().set_offset_from_scrollbar(point);
767 }
768
769 pub fn max_offset_for_scrollbar(&self) -> Point<Pixels> {
772 let state = self.0.borrow();
773 point(Pixels::ZERO, state.max_scroll_offset())
774 }
775
776 pub fn scroll_px_offset_for_scrollbar(&self) -> Point<Pixels> {
781 let state = &self.0.borrow();
782
783 if state.logical_scroll_top.is_none() && state.alignment == ListAlignment::Bottom {
784 return Point::new(px(0.), -state.max_scroll_offset());
785 }
786
787 let logical_scroll_top = state.logical_scroll_top();
788
789 let mut cursor = state.items.cursor::<ListItemSummary>(());
790 let summary: ListItemSummary =
791 cursor.summary(&Count(logical_scroll_top.item_ix), Bias::Right);
792 let offset = summary.height + logical_scroll_top.offset_in_item;
793
794 Point::new(px(0.), -offset)
795 }
796
797 pub fn viewport_bounds(&self) -> Bounds<Pixels> {
799 self.0.borrow().last_layout_bounds.unwrap_or_default()
800 }
801
802 pub fn item_is_above_viewport(&self, ix: usize) -> Option<bool> {
810 let viewport_bounds = self.0.borrow().last_layout_bounds?;
811
812 let scroll_top = self.logical_scroll_top();
813 if ix < scroll_top.item_ix {
814 return Some(true);
817 }
818
819 let item_bounds = self.bounds_for_item(ix)?;
820 Some(item_bounds.bottom() <= viewport_bounds.top())
821 }
822
823 pub fn item_is_below_viewport(&self, ix: usize) -> Option<bool> {
829 let viewport_bounds = self.0.borrow().last_layout_bounds?;
830
831 let scroll_top = self.logical_scroll_top();
832 if ix < scroll_top.item_ix {
833 return Some(false);
836 }
837
838 let item_bounds = self.bounds_for_item(ix)?;
839 Some(item_bounds.top() >= viewport_bounds.bottom())
840 }
841}
842
843impl StateInner {
844 fn rebase_pending_scroll(&mut self, scroll_top: ListOffset) {
848 let Some(pending) = self.pending_scroll.take() else {
849 return;
850 };
851 if scroll_top.item_ix >= self.items.summary().count {
852 return;
853 }
854
855 self.pending_scroll = match pending {
856 PendingScroll::Absolute { .. } => Some(PendingScroll::Absolute {
857 item_ix: scroll_top.item_ix,
858 offset: scroll_top.offset_in_item,
859 }),
860 PendingScroll::Proportional(_) => {
861 let mut cursor = self.items.cursor::<Count>(());
862 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
863 cursor
864 .item()
865 .and_then(|item| item.size_hint())
866 .filter(|size| size.height.0 > 0.0)
867 .map(|size| {
868 PendingScroll::Proportional(PendingScrollFraction {
869 item_ix: scroll_top.item_ix,
870 fraction: (scroll_top.offset_in_item.0 / size.height.0).clamp(0.0, 1.0),
871 })
872 })
873 }
874 };
875 }
876
877 fn max_scroll_offset(&self) -> Pixels {
878 let bounds = self.last_layout_bounds.unwrap_or_default();
879 let height = self
880 .scrollbar_drag_start_height
881 .unwrap_or_else(|| self.items.summary().height);
882 (height - bounds.size.height).max(px(0.))
883 }
884
885 fn visible_range(
886 items: &SumTree<ListItem>,
887 height: Pixels,
888 scroll_top: &ListOffset,
889 ) -> Range<usize> {
890 let mut cursor = items.cursor::<ListItemSummary>(());
891 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
892 let start_y = cursor.start().height + scroll_top.offset_in_item;
893 cursor.seek_forward(&Height(start_y + height), Bias::Left);
894 scroll_top.item_ix..cursor.start().count + 1
895 }
896
897 fn scroll(
898 &mut self,
899 scroll_top: &ListOffset,
900 height: Pixels,
901 delta: Point<Pixels>,
902 current_view: EntityId,
903 window: &mut Window,
904 cx: &mut App,
905 ) {
906 if self.reset {
909 return;
910 }
911
912 let padding = self.last_padding.unwrap_or_default();
913 let scroll_max =
914 (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
915 let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
916 .max(px(0.))
917 .min(scroll_max);
918
919 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
920 self.pending_scroll = None;
921 self.logical_scroll_top = None;
922 } else {
923 let (start, ..) =
924 self.items
925 .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
926 let scroll_top = ListOffset {
927 item_ix: start.count,
928 offset_in_item: new_scroll_top - start.height,
929 };
930 self.rebase_pending_scroll(scroll_top);
934 self.logical_scroll_top = Some(scroll_top);
935 }
936
937 if delta.y > px(0.) {
938 self.follow_state.stop_following();
939 }
940
941 if let Some(handler) = self.scroll_handler.as_mut() {
942 let visible_range = Self::visible_range(&self.items, height, scroll_top);
943 handler(
944 &ListScrollEvent {
945 visible_range,
946 count: self.items.summary().count,
947 is_scrolled: self.logical_scroll_top.is_some(),
948 is_following_tail: matches!(
949 self.follow_state,
950 FollowState::Tail { is_following: true }
951 ),
952 },
953 window,
954 cx,
955 );
956 }
957
958 cx.notify(current_view);
959 }
960
961 fn logical_scroll_top(&self) -> ListOffset {
962 self.logical_scroll_top
963 .unwrap_or_else(|| match self.alignment {
964 ListAlignment::Top => ListOffset {
965 item_ix: 0,
966 offset_in_item: px(0.),
967 },
968 ListAlignment::Bottom => ListOffset {
969 item_ix: self.items.summary().count,
970 offset_in_item: px(0.),
971 },
972 })
973 }
974
975 fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
976 let (start, ..) = self.items.find::<ListItemSummary, _>(
977 (),
978 &Count(logical_scroll_top.item_ix),
979 Bias::Right,
980 );
981 start.height + logical_scroll_top.offset_in_item
982 }
983
984 fn layout_all_items(
985 &mut self,
986 available_width: Pixels,
987 render_item: &mut RenderItemFn,
988 window: &mut Window,
989 cx: &mut App,
990 ) {
991 match &mut self.measuring_behavior {
992 ListMeasuringBehavior::Visible => {
993 return;
994 }
995 ListMeasuringBehavior::Measure(has_measured) => {
996 if *has_measured {
997 return;
998 }
999 *has_measured = true;
1000 }
1001 }
1002
1003 let mut cursor = self.items.cursor::<Count>(());
1004 let available_item_space = size(
1005 AvailableSpace::Definite(available_width),
1006 AvailableSpace::MinContent,
1007 );
1008
1009 let mut measured_items = Vec::default();
1010
1011 for (ix, item) in cursor.enumerate() {
1012 let size = item.size().unwrap_or_else(|| {
1013 let mut element = render_item(ix, window, cx);
1014 element.layout_as_root(available_item_space, window, cx)
1015 });
1016
1017 measured_items.push(ListItem::Measured {
1018 size,
1019 focus_handle: item.focus_handle(),
1020 });
1021 }
1022
1023 self.items = SumTree::from_iter(measured_items, ());
1024 }
1025
1026 fn layout_items(
1027 &mut self,
1028 available_width: Option<Pixels>,
1029 available_height: Pixels,
1030 padding: &Edges<Pixels>,
1031 render_item: &mut RenderItemFn,
1032 window: &mut Window,
1033 cx: &mut App,
1034 ) -> LayoutItemsResponse {
1035 let old_items = self.items.clone();
1036 let mut measured_items = VecDeque::new();
1037 let mut item_layouts = VecDeque::new();
1038 let mut rendered_height = padding.top;
1039 let mut max_item_width = px(0.);
1040 let mut scroll_top = self.logical_scroll_top();
1041
1042 if self.follow_state.is_following() {
1043 scroll_top = ListOffset {
1044 item_ix: self.items.summary().count,
1045 offset_in_item: px(0.),
1046 };
1047 self.logical_scroll_top = Some(scroll_top);
1048 }
1049
1050 let mut rendered_focused_item = false;
1051
1052 let available_item_space = size(
1053 available_width.map_or(AvailableSpace::MaxContent, |width| {
1054 AvailableSpace::Definite(width)
1055 }),
1056 AvailableSpace::MinContent,
1057 );
1058
1059 let mut cursor = old_items.cursor::<Count>(());
1060
1061 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1063 for (ix, item) in cursor.by_ref().enumerate() {
1064 let visible_height = rendered_height - scroll_top.offset_in_item;
1065 if visible_height >= available_height + self.overdraw {
1066 break;
1067 }
1068
1069 let mut size = item.size();
1071
1072 if visible_height < available_height || size.is_none() {
1074 let item_index = scroll_top.item_ix + ix;
1075 let mut element = render_item(item_index, window, cx);
1076 let element_size = element.layout_as_root(available_item_space, window, cx);
1077 size = Some(element_size);
1078
1079 if ix == 0 {
1082 if let Some(pending_scroll) = self.pending_scroll.take() {
1083 match pending_scroll {
1084 PendingScroll::Absolute { item_ix, offset }
1085 if item_ix == scroll_top.item_ix =>
1086 {
1087 scroll_top.offset_in_item = offset.min(element_size.height);
1088 self.logical_scroll_top = Some(scroll_top);
1089 }
1090 PendingScroll::Proportional(pending_scroll)
1091 if pending_scroll.item_ix == scroll_top.item_ix =>
1092 {
1093 scroll_top.offset_in_item =
1096 Pixels(pending_scroll.fraction * element_size.height.0);
1097 self.logical_scroll_top = Some(scroll_top);
1098 }
1099 _ => {}
1100 }
1101 }
1102 }
1103
1104 if visible_height < available_height {
1105 item_layouts.push_back(ItemLayout {
1106 index: item_index,
1107 element,
1108 size: element_size,
1109 });
1110 if item.contains_focused(window, cx) {
1111 rendered_focused_item = true;
1112 }
1113 }
1114 }
1115
1116 let size = size.unwrap();
1117 rendered_height += size.height;
1118 max_item_width = max_item_width.max(size.width);
1119 measured_items.push_back(ListItem::Measured {
1120 size,
1121 focus_handle: item.focus_handle(),
1122 });
1123 }
1124 rendered_height += padding.bottom;
1125
1126 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1128
1129 if rendered_height - scroll_top.offset_in_item < available_height {
1132 while rendered_height < available_height {
1133 cursor.prev();
1134 if let Some(item) = cursor.item() {
1135 let item_index = cursor.start().0;
1136 let mut element = render_item(item_index, window, cx);
1137 let element_size = element.layout_as_root(available_item_space, window, cx);
1138 let focus_handle = item.focus_handle();
1139 rendered_height += element_size.height;
1140 measured_items.push_front(ListItem::Measured {
1141 size: element_size,
1142 focus_handle,
1143 });
1144 item_layouts.push_front(ItemLayout {
1145 index: item_index,
1146 element,
1147 size: element_size,
1148 });
1149 if item.contains_focused(window, cx) {
1150 rendered_focused_item = true;
1151 }
1152 } else {
1153 break;
1154 }
1155 }
1156
1157 scroll_top = ListOffset {
1158 item_ix: cursor.start().0,
1159 offset_in_item: rendered_height - available_height,
1160 };
1161
1162 match self.alignment {
1163 ListAlignment::Top => {
1164 scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
1165 self.logical_scroll_top = Some(scroll_top);
1166 }
1167 ListAlignment::Bottom => {
1168 scroll_top = ListOffset {
1169 item_ix: cursor.start().0,
1170 offset_in_item: rendered_height - available_height,
1171 };
1172 self.logical_scroll_top = None;
1173 }
1174 };
1175 }
1176
1177 let mut leading_overdraw = scroll_top.offset_in_item;
1179 while leading_overdraw < self.overdraw {
1180 cursor.prev();
1181 if let Some(item) = cursor.item() {
1182 let size = if let ListItem::Measured { size, .. } = item {
1183 *size
1184 } else {
1185 let mut element = render_item(cursor.start().0, window, cx);
1186 element.layout_as_root(available_item_space, window, cx)
1187 };
1188
1189 leading_overdraw += size.height;
1190 measured_items.push_front(ListItem::Measured {
1191 size,
1192 focus_handle: item.focus_handle(),
1193 });
1194 } else {
1195 break;
1196 }
1197 }
1198
1199 let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
1200 let mut cursor = old_items.cursor::<Count>(());
1201 let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right);
1202 new_items.extend(measured_items, ());
1203 cursor.seek(&Count(measured_range.end), Bias::Right);
1204 new_items.append(cursor.suffix(), ());
1205 self.items = new_items;
1206
1207 if self.follow_state.has_stopped_following() {
1211 let padding = self.last_padding.unwrap_or_default();
1212 let total_height = self.items.summary().height + padding.top + padding.bottom;
1213 let scroll_offset = self.scroll_top(&scroll_top);
1214 if scroll_offset + available_height >= total_height - px(1.0) {
1215 self.follow_state.start_following();
1216 }
1217 }
1218
1219 if !rendered_focused_item {
1223 let mut cursor = self
1224 .items
1225 .filter::<_, Count>((), |summary| summary.has_focus_handles);
1226 cursor.next();
1227 while let Some(item) = cursor.item() {
1228 if item.contains_focused(window, cx) {
1229 let item_index = cursor.start().0;
1230 let mut element = render_item(cursor.start().0, window, cx);
1231 let size = element.layout_as_root(available_item_space, window, cx);
1232 item_layouts.push_back(ItemLayout {
1233 index: item_index,
1234 element,
1235 size,
1236 });
1237 break;
1238 }
1239 cursor.next();
1240 }
1241 }
1242
1243 LayoutItemsResponse {
1244 max_item_width,
1245 scroll_top,
1246 item_layouts,
1247 }
1248 }
1249
1250 fn prepaint_items(
1251 &mut self,
1252 bounds: Bounds<Pixels>,
1253 padding: Edges<Pixels>,
1254 autoscroll: bool,
1255 render_item: &mut RenderItemFn,
1256 window: &mut Window,
1257 cx: &mut App,
1258 ) -> Result<LayoutItemsResponse, ListOffset> {
1259 window.transact(|window| {
1260 match self.measuring_behavior {
1261 ListMeasuringBehavior::Measure(has_measured) if !has_measured => {
1262 self.layout_all_items(bounds.size.width, render_item, window, cx);
1263 }
1264 _ => {}
1265 }
1266
1267 let mut layout_response = self.layout_items(
1268 Some(bounds.size.width),
1269 bounds.size.height,
1270 &padding,
1271 render_item,
1272 window,
1273 cx,
1274 );
1275
1276 window.take_autoscroll();
1278
1279 if bounds.size.height > padding.top + padding.bottom {
1281 let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
1282 item_origin.y -= layout_response.scroll_top.offset_in_item;
1283 for item in &mut layout_response.item_layouts {
1284 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1285 item.element.prepaint_at(item_origin, window, cx);
1286 });
1287
1288 if let Some(autoscroll_bounds) = window.take_autoscroll()
1289 && autoscroll
1290 {
1291 if autoscroll_bounds.top() < bounds.top() {
1292 let mut item_ix = item.index;
1293 let mut offset_in_item = autoscroll_bounds.top() - item_origin.y;
1294
1295 if offset_in_item < Pixels::ZERO {
1300 let mut cursor = self.items.cursor::<Count>(());
1301 cursor.seek(&Count(item_ix), Bias::Right);
1302 while offset_in_item < Pixels::ZERO {
1303 cursor.prev();
1304 let Some(prev_item) = cursor.item() else {
1305 offset_in_item = Pixels::ZERO;
1306 break;
1307 };
1308 let size = prev_item.size().unwrap_or_else(|| {
1309 let mut element = render_item(cursor.start().0, window, cx);
1310 let item_available_size = size(
1311 bounds.size.width.into(),
1312 AvailableSpace::MinContent,
1313 );
1314 element.layout_as_root(item_available_size, window, cx)
1315 });
1316 item_ix = cursor.start().0;
1317 offset_in_item += size.height;
1318 }
1319 }
1320
1321 return Err(ListOffset {
1322 item_ix,
1323 offset_in_item,
1324 });
1325 } else if autoscroll_bounds.bottom() > bounds.bottom() {
1326 let mut cursor = self.items.cursor::<Count>(());
1327 cursor.seek(&Count(item.index), Bias::Right);
1328 let mut height = bounds.size.height - padding.top - padding.bottom;
1329
1330 height -= autoscroll_bounds.bottom() - item_origin.y;
1332
1333 while height > Pixels::ZERO {
1335 cursor.prev();
1336 let Some(item) = cursor.item() else { break };
1337
1338 let size = item.size().unwrap_or_else(|| {
1339 let mut item = render_item(cursor.start().0, window, cx);
1340 let item_available_size =
1341 size(bounds.size.width.into(), AvailableSpace::MinContent);
1342 item.layout_as_root(item_available_size, window, cx)
1343 });
1344 height -= size.height;
1345 }
1346
1347 return Err(ListOffset {
1348 item_ix: cursor.start().0,
1349 offset_in_item: if height < Pixels::ZERO {
1350 -height
1351 } else {
1352 Pixels::ZERO
1353 },
1354 });
1355 }
1356 }
1357
1358 item_origin.y += item.size.height;
1359 }
1360 } else {
1361 layout_response.item_layouts.clear();
1362 }
1363
1364 Ok(layout_response)
1365 })
1366 }
1367
1368 fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
1371 let Some(bounds) = self.last_layout_bounds else {
1372 return;
1373 };
1374 let height = bounds.size.height;
1375
1376 let padding = self.last_padding.unwrap_or_default();
1377 let content_height = self
1380 .scrollbar_drag_start_height
1381 .unwrap_or_else(|| self.items.summary().height);
1382 let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
1383 let new_scroll_top = (-point.y).max(px(0.)).min(scroll_max);
1384
1385 let dragged_to_end =
1388 scroll_max > px(0.) && new_scroll_top >= (scroll_max - px(1.0)).max(px(0.));
1389 if dragged_to_end && matches!(self.follow_state, FollowState::Tail { .. }) {
1390 self.follow_state = FollowState::Tail { is_following: true };
1391 let item_count = self.items.summary().count;
1392 self.pending_scroll = None;
1393 self.logical_scroll_top = Some(ListOffset {
1394 item_ix: item_count,
1395 offset_in_item: px(0.),
1396 });
1397 return;
1398 }
1399
1400 self.follow_state.stop_following();
1401
1402 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
1403 self.pending_scroll = None;
1404 self.logical_scroll_top = None;
1405 } else {
1406 let (start, _, _) =
1407 self.items
1408 .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
1409
1410 let scroll_top = ListOffset {
1411 item_ix: start.count,
1412 offset_in_item: new_scroll_top - start.height,
1413 };
1414 self.rebase_pending_scroll(scroll_top);
1415 self.logical_scroll_top = Some(scroll_top);
1416 }
1417 }
1418}
1419
1420impl std::fmt::Debug for ListItem {
1421 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1422 match self {
1423 Self::Unmeasured { .. } => write!(f, "Unrendered"),
1424 Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
1425 }
1426 }
1427}
1428
1429#[derive(Debug, Clone, Copy, Default)]
1432pub struct ListOffset {
1433 pub item_ix: usize,
1435 pub offset_in_item: Pixels,
1437}
1438
1439impl Element for List {
1440 type RequestLayoutState = ();
1441 type PrepaintState = ListPrepaintState;
1442
1443 fn id(&self) -> Option<crate::ElementId> {
1444 None
1445 }
1446
1447 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1448 None
1449 }
1450
1451 fn request_layout(
1452 &mut self,
1453 _id: Option<&GlobalElementId>,
1454 window: &mut Window,
1455 cx: &mut App,
1456 ) -> (crate::LayoutId, Self::RequestLayoutState) {
1457 let layout_id = match self.sizing_behavior {
1458 ListSizingBehavior::Infer => {
1459 let mut style = Style::default();
1460 style.overflow.y = Overflow::Scroll;
1461 style.refine(&self.style);
1462 window.with_text_style(style.text_style().cloned(), |window| {
1463 let state = &mut *self.state.0.borrow_mut();
1464
1465 let available_height = if let Some(last_bounds) = state.last_layout_bounds {
1466 last_bounds.size.height
1467 } else {
1468 state.overdraw
1471 };
1472 let padding = style.padding.to_pixels(
1473 state.last_layout_bounds.unwrap_or_default().size.into(),
1474 window.rem_size(),
1475 );
1476
1477 let layout_response = state.layout_items(
1478 None,
1479 available_height,
1480 &padding,
1481 &mut self.render_item,
1482 window,
1483 cx,
1484 );
1485 let max_element_width = layout_response.max_item_width;
1486
1487 let summary = state.items.summary();
1488 let total_height = summary.height;
1489
1490 window.request_measured_layout(
1491 style,
1492 move |known_dimensions, available_space, _window, _cx| {
1493 let width =
1494 known_dimensions
1495 .width
1496 .unwrap_or(match available_space.width {
1497 AvailableSpace::Definite(x) => x,
1498 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1499 max_element_width
1500 }
1501 });
1502 let height = match available_space.height {
1503 AvailableSpace::Definite(height) => total_height.min(height),
1504 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1505 total_height
1506 }
1507 };
1508 size(width, height)
1509 },
1510 )
1511 })
1512 }
1513 ListSizingBehavior::Auto => {
1514 let mut style = Style::default();
1515 style.refine(&self.style);
1516 window.with_text_style(style.text_style().cloned(), |window| {
1517 window.request_layout(style, None, cx)
1518 })
1519 }
1520 };
1521 (layout_id, ())
1522 }
1523
1524 fn prepaint(
1525 &mut self,
1526 _id: Option<&GlobalElementId>,
1527 bounds: Bounds<Pixels>,
1528 _: &mut Self::RequestLayoutState,
1529 window: &mut Window,
1530 cx: &mut App,
1531 ) -> ListPrepaintState {
1532 let state = &mut *self.state.0.borrow_mut();
1533 state.reset = false;
1534
1535 let mut style = Style::default();
1536 style.refine(&self.style);
1537
1538 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1539
1540 if state
1542 .last_layout_bounds
1543 .is_none_or(|last_bounds| last_bounds.size.width != bounds.size.width)
1544 {
1545 let new_items = SumTree::from_iter(
1546 state.items.iter().map(|item| ListItem::Unmeasured {
1547 size_hint: None,
1548 focus_handle: item.focus_handle(),
1549 }),
1550 (),
1551 );
1552
1553 state.items = new_items;
1554 state.measuring_behavior.reset();
1555 }
1556
1557 let padding = style
1558 .padding
1559 .to_pixels(bounds.size.into(), window.rem_size());
1560 let layout =
1561 match state.prepaint_items(bounds, padding, true, &mut self.render_item, window, cx) {
1562 Ok(layout) => layout,
1563 Err(autoscroll_request) => {
1564 state.logical_scroll_top = Some(autoscroll_request);
1565 state
1566 .prepaint_items(bounds, padding, false, &mut self.render_item, window, cx)
1567 .unwrap()
1568 }
1569 };
1570
1571 state.last_layout_bounds = Some(bounds);
1572 state.last_padding = Some(padding);
1573 ListPrepaintState { hitbox, layout }
1574 }
1575
1576 fn paint(
1577 &mut self,
1578 _id: Option<&GlobalElementId>,
1579 bounds: Bounds<crate::Pixels>,
1580 _: &mut Self::RequestLayoutState,
1581 prepaint: &mut Self::PrepaintState,
1582 window: &mut Window,
1583 cx: &mut App,
1584 ) {
1585 let current_view = window.current_view();
1586
1587 let list_state = self.state.clone();
1593 let height = bounds.size.height;
1594 let scroll_top = prepaint.layout.scroll_top;
1595 let hitbox_id = prepaint.hitbox.id;
1596 let mut accumulated_scroll_delta = ScrollDelta::default();
1597 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
1598 if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
1599 accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
1600 let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1601 list_state.0.borrow_mut().scroll(
1602 &scroll_top,
1603 height,
1604 pixel_delta,
1605 current_view,
1606 window,
1607 cx,
1608 )
1609 }
1610 });
1611
1612 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1613 for item in &mut prepaint.layout.item_layouts {
1614 item.element.paint(window, cx);
1615 }
1616 });
1617 }
1618}
1619
1620impl IntoElement for List {
1621 type Element = Self;
1622
1623 fn into_element(self) -> Self::Element {
1624 self
1625 }
1626}
1627
1628impl Styled for List {
1629 fn style(&mut self) -> &mut StyleRefinement {
1630 &mut self.style
1631 }
1632}
1633
1634impl sum_tree::Item for ListItem {
1635 type Summary = ListItemSummary;
1636
1637 fn summary(&self, _: ()) -> Self::Summary {
1638 match self {
1639 ListItem::Unmeasured {
1640 size_hint,
1641 focus_handle,
1642 } => ListItemSummary {
1643 count: 1,
1644 rendered_count: 0,
1645 unrendered_count: 1,
1646 height: if let Some(size) = size_hint {
1647 size.height
1648 } else {
1649 px(0.)
1650 },
1651 has_focus_handles: focus_handle.is_some(),
1652 has_unknown_height: size_hint.is_none(),
1653 },
1654 ListItem::Measured {
1655 size, focus_handle, ..
1656 } => ListItemSummary {
1657 count: 1,
1658 rendered_count: 1,
1659 unrendered_count: 0,
1660 height: size.height,
1661 has_focus_handles: focus_handle.is_some(),
1662 has_unknown_height: false,
1663 },
1664 }
1665 }
1666}
1667
1668impl sum_tree::ContextLessSummary for ListItemSummary {
1669 fn zero() -> Self {
1670 Default::default()
1671 }
1672
1673 fn add_summary(&mut self, summary: &Self) {
1674 self.count += summary.count;
1675 self.rendered_count += summary.rendered_count;
1676 self.unrendered_count += summary.unrendered_count;
1677 self.height += summary.height;
1678 self.has_focus_handles |= summary.has_focus_handles;
1679 self.has_unknown_height |= summary.has_unknown_height;
1680 }
1681}
1682
1683impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1684 fn zero(_cx: ()) -> Self {
1685 Default::default()
1686 }
1687
1688 fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1689 self.0 += summary.count;
1690 }
1691}
1692
1693impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1694 fn zero(_cx: ()) -> Self {
1695 Default::default()
1696 }
1697
1698 fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1699 self.0 += summary.height;
1700 }
1701}
1702
1703impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1704 fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1705 self.0.partial_cmp(&other.count).unwrap()
1706 }
1707}
1708
1709impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1710 fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1711 self.0.partial_cmp(&other.height).unwrap()
1712 }
1713}
1714
1715#[cfg(test)]
1716mod test {
1717
1718 use gpui::{ScrollDelta, ScrollWheelEvent};
1719 use std::cell::Cell;
1720 use std::rc::Rc;
1721
1722 use crate::{
1723 self as gpui, AppContext, Bounds, Context, Element, FollowMode, InteractiveElement,
1724 IntoElement, ListState, Render, Styled, TestAppContext, Window, canvas, div, list, point,
1725 px, size,
1726 };
1727
1728 #[gpui::test]
1729 fn test_autoscroll_above_item_top_renders_items_above(cx: &mut TestAppContext) {
1730 let cx = cx.add_empty_window();
1731
1732 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1733 state.scroll_to(gpui::ListOffset {
1734 item_ix: 2,
1735 offset_in_item: px(0.),
1736 });
1737
1738 struct TestView(ListState);
1739 impl Render for TestView {
1740 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1741 list(self.0.clone(), |ix, _, _| {
1742 if ix == 2 {
1743 canvas(
1746 |bounds, window, _| {
1747 window.request_autoscroll(Bounds::from_corners(
1748 point(bounds.left(), bounds.top() - px(30.)),
1749 point(bounds.right(), bounds.top() + px(5.)),
1750 ));
1751 },
1752 |_, _, _, _| {},
1753 )
1754 .h(px(20.))
1755 .w_full()
1756 .into_any()
1757 } else {
1758 div().h(px(20.)).w_full().into_any()
1759 }
1760 })
1761 .w_full()
1762 .h_full()
1763 }
1764 }
1765
1766 cx.draw(point(px(0.), px(0.)), size(px(100.), px(60.)), |_, cx| {
1767 cx.new(|_| TestView(state.clone())).into_any_element()
1768 });
1769
1770 let scroll_top = state.logical_scroll_top();
1772 assert!(
1773 scroll_top.offset_in_item >= px(0.),
1774 "offset_in_item must never be negative (would leave blank space above), got {:?}",
1775 scroll_top.offset_in_item,
1776 );
1777 assert_eq!(scroll_top.item_ix, 0);
1778 assert_eq!(scroll_top.offset_in_item, px(10.));
1779 }
1780
1781 #[gpui::test]
1782 fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
1783 let cx = cx.add_empty_window();
1784
1785 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1786
1787 state.scroll_to(gpui::ListOffset {
1789 item_ix: 0,
1790 offset_in_item: px(0.0),
1791 });
1792
1793 struct TestView(ListState);
1794 impl Render for TestView {
1795 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1796 list(self.0.clone(), |_, _, _| {
1797 div().h(px(10.)).w_full().into_any()
1798 })
1799 .w_full()
1800 .h_full()
1801 }
1802 }
1803
1804 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1806 cx.new(|_| TestView(state.clone())).into_any_element()
1807 });
1808
1809 state.reset(5);
1811
1812 cx.simulate_event(ScrollWheelEvent {
1814 position: point(px(1.), px(1.)),
1815 delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
1816 ..Default::default()
1817 });
1818
1819 assert_eq!(state.logical_scroll_top().item_ix, 0);
1821 assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
1822 }
1823
1824 #[gpui::test]
1825 fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
1826 let cx = cx.add_empty_window();
1827
1828 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1829
1830 struct TestView(ListState);
1831 impl Render for TestView {
1832 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1833 list(self.0.clone(), |_, _, _| {
1834 div().h(px(20.)).w_full().into_any()
1835 })
1836 .w_full()
1837 .h_full()
1838 }
1839 }
1840
1841 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1843 cx.new(|_| TestView(state.clone())).into_any_element()
1844 });
1845
1846 state.scroll_by(px(30.));
1848
1849 let offset = state.logical_scroll_top();
1851 assert_eq!(offset.item_ix, 1);
1852 assert_eq!(offset.offset_in_item, px(10.));
1853
1854 state.scroll_by(px(-30.));
1856
1857 let offset = state.logical_scroll_top();
1859 assert_eq!(offset.item_ix, 0);
1860 assert_eq!(offset.offset_in_item, px(0.));
1861
1862 state.scroll_by(px(0.));
1864 let offset = state.logical_scroll_top();
1865 assert_eq!(offset.item_ix, 0);
1866 assert_eq!(offset.offset_in_item, px(0.));
1867 }
1868
1869 #[gpui::test]
1870 fn test_child_scroll_handler_can_stop_list_scroll(cx: &mut TestAppContext) {
1871 let cx = cx.add_empty_window();
1872
1873 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1874 let child_saw_event = Rc::new(Cell::new(false));
1875
1876 struct TestView {
1877 state: ListState,
1878 child_saw_event: Rc<Cell<bool>>,
1879 }
1880 impl Render for TestView {
1881 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1882 let child_saw_event = self.child_saw_event.clone();
1883 list(self.state.clone(), move |_, _, _| {
1884 let child_saw_event = child_saw_event.clone();
1885 div()
1886 .h(px(20.))
1887 .w_full()
1888 .on_scroll_wheel(move |_, _, cx| {
1889 child_saw_event.set(true);
1890 cx.stop_propagation();
1891 })
1892 .into_any()
1893 })
1894 .w_full()
1895 .h_full()
1896 }
1897 }
1898
1899 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1900 cx.new(|_| TestView {
1901 state: state.clone(),
1902 child_saw_event: child_saw_event.clone(),
1903 })
1904 .into_any_element()
1905 });
1906
1907 cx.simulate_event(ScrollWheelEvent {
1908 position: point(px(50.), px(10.)),
1909 delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
1910 ..Default::default()
1911 });
1912
1913 assert!(
1914 child_saw_event.get(),
1915 "the child's scroll-wheel handler should run"
1916 );
1917 let offset = state.logical_scroll_top();
1919 assert_eq!(offset.item_ix, 0);
1920 assert_eq!(offset.offset_in_item, px(0.));
1921 }
1922
1923 struct TestListView(ListState);
1924 impl Render for TestListView {
1925 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1926 list(self.0.clone(), |_, _, _| {
1927 div().h(px(20.)).w_full().into_any()
1928 })
1929 .w_full()
1930 .h_full()
1931 }
1932 }
1933
1934 #[gpui::test]
1935 fn test_item_viewport_queries_return_none_before_layout(_cx: &mut TestAppContext) {
1936 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
1937
1938 assert_eq!(state.item_is_above_viewport(0), None);
1939 assert_eq!(state.item_is_below_viewport(0), None);
1940 }
1941
1942 #[gpui::test]
1943 fn test_item_viewport_queries_before_logical_scroll_top(cx: &mut TestAppContext) {
1944 let cx = cx.add_empty_window();
1945
1946 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
1947
1948 state.scroll_to(gpui::ListOffset {
1949 item_ix: 2,
1950 offset_in_item: px(0.),
1951 });
1952 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1953 cx.new(|_| TestListView(state.clone())).into_any_element()
1954 });
1955
1956 assert_eq!(state.item_is_above_viewport(1), Some(true));
1957 assert_eq!(state.item_is_below_viewport(1), Some(false));
1958 }
1959
1960 #[gpui::test]
1961 fn test_item_viewport_queries_measured_item_inside_viewport(cx: &mut TestAppContext) {
1962 let cx = cx.add_empty_window();
1963
1964 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
1965
1966 state.scroll_to(gpui::ListOffset {
1967 item_ix: 2,
1968 offset_in_item: px(0.),
1969 });
1970 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1971 cx.new(|_| TestListView(state.clone())).into_any_element()
1972 });
1973
1974 assert_eq!(state.item_is_above_viewport(2), Some(false));
1975 assert_eq!(state.item_is_below_viewport(2), Some(false));
1976 }
1977
1978 #[gpui::test]
1979 fn test_item_viewport_queries_measured_item_above_viewport(cx: &mut TestAppContext) {
1980 let cx = cx.add_empty_window();
1981
1982 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
1983
1984 state.scroll_to(gpui::ListOffset {
1985 item_ix: 2,
1986 offset_in_item: px(20.),
1987 });
1988 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1989 cx.new(|_| TestListView(state.clone())).into_any_element()
1990 });
1991
1992 assert_eq!(state.item_is_above_viewport(2), Some(true));
1993 assert_eq!(state.item_is_below_viewport(2), Some(false));
1994 }
1995
1996 #[gpui::test]
1997 fn test_item_viewport_queries_measured_item_below_viewport(cx: &mut TestAppContext) {
1998 let cx = cx.add_empty_window();
1999
2000 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2001
2002 state.scroll_to(gpui::ListOffset {
2003 item_ix: 2,
2004 offset_in_item: px(0.),
2005 });
2006 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2007 cx.new(|_| TestListView(state.clone())).into_any_element()
2008 });
2009
2010 assert_eq!(state.item_is_above_viewport(3), Some(false));
2011 assert_eq!(state.item_is_below_viewport(3), Some(true));
2012 }
2013
2014 #[gpui::test]
2015 fn test_item_viewport_queries_remain_stable_with_zero_height_viewport(cx: &mut TestAppContext) {
2016 let cx = cx.add_empty_window();
2017
2018 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2019
2020 state.scroll_to(gpui::ListOffset {
2021 item_ix: 2,
2022 offset_in_item: px(0.),
2023 });
2024 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2025 cx.new(|_| TestListView(state.clone())).into_any_element()
2026 });
2027
2028 assert_eq!(state.item_is_above_viewport(3), Some(false));
2029 assert_eq!(state.item_is_below_viewport(3), Some(true));
2030
2031 cx.draw(point(px(0.), px(0.)), size(px(100.), px(0.)), |_, cx| {
2036 cx.new(|_| TestListView(state.clone())).into_any_element()
2037 });
2038
2039 assert_eq!(state.item_is_above_viewport(1), Some(true));
2040 assert_eq!(state.item_is_below_viewport(1), Some(false));
2041 assert_eq!(state.item_is_above_viewport(3), Some(false));
2042 assert_eq!(state.item_is_below_viewport(3), Some(true));
2043 }
2044
2045 #[gpui::test]
2046 fn test_item_viewport_queries_after_scroll_to_end_before_layout(cx: &mut TestAppContext) {
2047 let cx = cx.add_empty_window();
2048
2049 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2050
2051 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2052 cx.new(|_| TestListView(state.clone())).into_any_element()
2053 });
2054
2055 state.scroll_to_end();
2056
2057 assert_eq!(state.logical_scroll_top().item_ix, state.item_count());
2058 assert_eq!(state.item_is_above_viewport(0), Some(true));
2059 assert_eq!(state.item_is_below_viewport(0), Some(false));
2060 }
2061
2062 #[gpui::test]
2063 fn test_measure_all_after_width_change(cx: &mut TestAppContext) {
2064 let cx = cx.add_empty_window();
2065
2066 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2067
2068 struct TestView(ListState);
2069 impl Render for TestView {
2070 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2071 list(self.0.clone(), |_, _, _| {
2072 div().h(px(50.)).w_full().into_any()
2073 })
2074 .w_full()
2075 .h_full()
2076 }
2077 }
2078
2079 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2080
2081 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2084 view.clone().into_any_element()
2085 });
2086 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2087
2088 cx.draw(point(px(0.), px(0.)), size(px(200.), px(200.)), |_, _| {
2092 view.into_any_element()
2093 });
2094 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2095 }
2096
2097 #[gpui::test]
2098 fn test_remeasure(cx: &mut TestAppContext) {
2099 let cx = cx.add_empty_window();
2100
2101 let item_height = Rc::new(Cell::new(100usize));
2105 let state = ListState::new(10, crate::ListAlignment::Top, px(10.));
2106
2107 struct TestView {
2108 state: ListState,
2109 item_height: Rc<Cell<usize>>,
2110 }
2111
2112 impl Render for TestView {
2113 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2114 let height = self.item_height.get();
2115 list(self.state.clone(), move |_, _, _| {
2116 div().h(px(height as f32)).w_full().into_any()
2117 })
2118 .w_full()
2119 .h_full()
2120 }
2121 }
2122
2123 let state_clone = state.clone();
2124 let item_height_clone = item_height.clone();
2125 let view = cx.update(|_, cx| {
2126 cx.new(|_| TestView {
2127 state: state_clone,
2128 item_height: item_height_clone,
2129 })
2130 });
2131
2132 state.scroll_to(gpui::ListOffset {
2135 item_ix: 2,
2136 offset_in_item: px(40.),
2137 });
2138
2139 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2140 view.clone().into_any_element()
2141 });
2142
2143 let offset = state.logical_scroll_top();
2144 assert_eq!(offset.item_ix, 2);
2145 assert_eq!(offset.offset_in_item, px(40.));
2146
2147 item_height.set(50);
2152 state.remeasure();
2153
2154 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2155 view.into_any_element()
2156 });
2157
2158 let offset = state.logical_scroll_top();
2159 assert_eq!(offset.item_ix, 2);
2160 assert_eq!(offset.offset_in_item, px(20.));
2161 }
2162
2163 #[gpui::test]
2164 fn test_remeasure_item_preserves_scroll_offset(cx: &mut TestAppContext) {
2165 let cx = cx.add_empty_window();
2166
2167 let item_height = Rc::new(Cell::new(100usize));
2168 let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2169
2170 struct TestView {
2171 state: ListState,
2172 item_height: Rc<Cell<usize>>,
2173 }
2174
2175 impl Render for TestView {
2176 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2177 let height = self.item_height.get();
2178 list(self.state.clone(), move |index, _, _| {
2179 let height = if index == 5 { height } else { 100 };
2180 div().h(px(height as f32)).w_full().into_any()
2181 })
2182 .w_full()
2183 .h_full()
2184 }
2185 }
2186
2187 let state_clone = state.clone();
2188 let item_height_clone = item_height.clone();
2189 let view = cx.update(|_, cx| {
2190 cx.new(|_| TestView {
2191 state: state_clone,
2192 item_height: item_height_clone,
2193 })
2194 });
2195
2196 state.scroll_to(gpui::ListOffset {
2197 item_ix: 5,
2198 offset_in_item: px(40.),
2199 });
2200
2201 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2202 view.clone().into_any_element()
2203 });
2204
2205 item_height.set(200);
2206 state.remeasure_items(5..6);
2207
2208 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2209 view.into_any_element()
2210 });
2211
2212 let offset = state.logical_scroll_top();
2213 assert_eq!(offset.item_ix, 5);
2214 assert_eq!(offset.offset_in_item, px(40.));
2215 }
2216
2217 #[gpui::test]
2218 fn test_remeasure_then_scroll_does_not_revert_scroll_position(cx: &mut TestAppContext) {
2219 let cx = cx.add_empty_window();
2220
2221 let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2222
2223 struct TestView(ListState);
2224 impl Render for TestView {
2225 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2226 list(self.0.clone(), |_, _, _| {
2227 div().h(px(100.)).w_full().into_any()
2228 })
2229 .w_full()
2230 .h_full()
2231 }
2232 }
2233
2234 let view = {
2235 let state = state.clone();
2236 cx.update(|_, cx| cx.new(|_| TestView(state)))
2237 };
2238
2239 state.scroll_to(gpui::ListOffset {
2240 item_ix: 5,
2241 offset_in_item: px(40.),
2242 });
2243
2244 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2245 view.clone().into_any_element()
2246 });
2247
2248 state.remeasure_items(5..6);
2249
2250 cx.simulate_event(ScrollWheelEvent {
2251 position: point(px(50.), px(100.)),
2252 delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2253 ..Default::default()
2254 });
2255
2256 let offset = state.logical_scroll_top();
2257 assert_eq!(offset.item_ix, 5);
2258 assert_eq!(offset.offset_in_item, px(70.));
2259
2260 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2261 view.into_any_element()
2262 });
2263
2264 let offset = state.logical_scroll_top();
2265 assert_eq!(offset.item_ix, 5);
2266 assert_eq!(
2267 offset.offset_in_item,
2268 px(70.),
2269 "scrolling after a remeasure should not be reverted by the stale pending scroll"
2270 );
2271 }
2272
2273 #[gpui::test]
2274 fn test_scroll_after_remeasure_clamps_to_shrunk_item_height(cx: &mut TestAppContext) {
2275 let cx = cx.add_empty_window();
2276
2277 let item_height = Rc::new(Cell::new(100usize));
2278 let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2279
2280 struct TestView {
2281 state: ListState,
2282 item_height: Rc<Cell<usize>>,
2283 }
2284
2285 impl Render for TestView {
2286 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2287 let height = self.item_height.get();
2288 list(self.state.clone(), move |index, _, _| {
2289 let height = if index == 5 { height } else { 100 };
2290 div().h(px(height as f32)).w_full().into_any()
2291 })
2292 .w_full()
2293 .h_full()
2294 }
2295 }
2296
2297 let view = {
2298 let state = state.clone();
2299 let item_height = item_height.clone();
2300 cx.update(|_, cx| cx.new(|_| TestView { state, item_height }))
2301 };
2302
2303 state.scroll_to(gpui::ListOffset {
2304 item_ix: 5,
2305 offset_in_item: px(40.),
2306 });
2307
2308 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2309 view.clone().into_any_element()
2310 });
2311
2312 item_height.set(50);
2314 state.remeasure_items(5..6);
2315
2316 cx.simulate_event(ScrollWheelEvent {
2319 position: point(px(50.), px(100.)),
2320 delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2321 ..Default::default()
2322 });
2323
2324 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2325 view.into_any_element()
2326 });
2327
2328 let offset = state.logical_scroll_top();
2331 assert_eq!(offset.item_ix, 5);
2332 assert_eq!(offset.offset_in_item, px(50.));
2333 }
2334
2335 #[gpui::test]
2336 fn test_follow_tail_stays_at_bottom_as_items_grow(cx: &mut TestAppContext) {
2337 let cx = cx.add_empty_window();
2338
2339 let item_height = Rc::new(Cell::new(50usize));
2342 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2343
2344 struct TestView {
2345 state: ListState,
2346 item_height: Rc<Cell<usize>>,
2347 }
2348 impl Render for TestView {
2349 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2350 let height = self.item_height.get();
2351 list(self.state.clone(), move |_, _, _| {
2352 div().h(px(height as f32)).w_full().into_any()
2353 })
2354 .w_full()
2355 .h_full()
2356 }
2357 }
2358
2359 let state_clone = state.clone();
2360 let item_height_clone = item_height.clone();
2361 let view = cx.update(|_, cx| {
2362 cx.new(|_| TestView {
2363 state: state_clone,
2364 item_height: item_height_clone,
2365 })
2366 });
2367
2368 state.set_follow_mode(FollowMode::Tail);
2369
2370 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2373 view.clone().into_any_element()
2374 });
2375
2376 let offset = state.logical_scroll_top();
2379 assert_eq!(offset.item_ix, 6);
2380 assert_eq!(offset.offset_in_item, px(0.));
2381 assert!(state.is_following_tail());
2382
2383 item_height.set(80);
2386 state.remeasure();
2387
2388 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2389 view.into_any_element()
2390 });
2391
2392 let offset = state.logical_scroll_top();
2399 assert_eq!(offset.item_ix, 7);
2400 assert_eq!(offset.offset_in_item, px(40.));
2401 assert!(state.is_following_tail());
2402 }
2403
2404 #[gpui::test]
2405 fn test_pause_following_tail_reengages_when_still_at_bottom(cx: &mut TestAppContext) {
2406 let cx = cx.add_empty_window();
2407
2408 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2410
2411 struct TestView(ListState);
2412 impl Render for TestView {
2413 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2414 list(self.0.clone(), |_, _, _| {
2415 div().h(px(50.)).w_full().into_any()
2416 })
2417 .w_full()
2418 .h_full()
2419 }
2420 }
2421
2422 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2423 state.set_follow_mode(FollowMode::Tail);
2424
2425 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2426 view.clone().into_any_element()
2427 });
2428 assert!(state.is_following_tail());
2429
2430 state.pause_following_tail();
2434 assert!(!state.is_following_tail());
2435
2436 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2437 view.into_any_element()
2438 });
2439 assert!(
2440 state.is_following_tail(),
2441 "pausing while at the bottom must re-engage follow-tail on the next layout"
2442 );
2443 }
2444
2445 #[gpui::test]
2446 fn test_pause_following_tail_freezes_off_bottom(cx: &mut TestAppContext) {
2447 let cx = cx.add_empty_window();
2448
2449 let item_height = Rc::new(Cell::new(50usize));
2452 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2453
2454 struct TestView {
2455 state: ListState,
2456 item_height: Rc<Cell<usize>>,
2457 }
2458 impl Render for TestView {
2459 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2460 let height = self.item_height.get();
2461 list(self.state.clone(), move |_, _, _| {
2462 div().h(px(height as f32)).w_full().into_any()
2463 })
2464 .w_full()
2465 .h_full()
2466 }
2467 }
2468
2469 let view = cx.update(|_, cx| {
2470 cx.new(|_| TestView {
2471 state: state.clone(),
2472 item_height: item_height.clone(),
2473 })
2474 });
2475 state.set_follow_mode(FollowMode::Tail);
2476
2477 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2479 view.clone().into_any_element()
2480 });
2481 assert_eq!(state.logical_scroll_top().item_ix, 6);
2482 assert!(state.is_following_tail());
2483
2484 state.pause_following_tail();
2488 item_height.set(80);
2489 state.remeasure();
2490 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2491 view.clone().into_any_element()
2492 });
2493 let offset = state.logical_scroll_top();
2494 assert_eq!(offset.item_ix, 6);
2495 assert_eq!(offset.offset_in_item, px(0.));
2496 assert!(
2497 !state.is_following_tail(),
2498 "a paused list must not re-engage while the frozen top is off the bottom"
2499 );
2500
2501 item_height.set(50);
2504 state.remeasure();
2505 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2506 view.into_any_element()
2507 });
2508 assert!(
2509 state.is_following_tail(),
2510 "returning to the bottom must restore follow-tail"
2511 );
2512 }
2513
2514 #[gpui::test]
2515 fn test_follow_tail_disengages_on_user_scroll(cx: &mut TestAppContext) {
2516 let cx = cx.add_empty_window();
2517
2518 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2520
2521 struct TestView(ListState);
2522 impl Render for TestView {
2523 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2524 list(self.0.clone(), |_, _, _| {
2525 div().h(px(50.)).w_full().into_any()
2526 })
2527 .w_full()
2528 .h_full()
2529 }
2530 }
2531
2532 state.set_follow_mode(FollowMode::Tail);
2533
2534 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, cx| {
2536 cx.new(|_| TestView(state.clone())).into_any_element()
2537 });
2538 assert!(state.is_following_tail());
2539
2540 cx.simulate_event(ScrollWheelEvent {
2543 position: point(px(50.), px(100.)),
2544 delta: ScrollDelta::Pixels(point(px(0.), px(100.))),
2545 ..Default::default()
2546 });
2547
2548 assert!(
2549 !state.is_following_tail(),
2550 "follow-tail should disengage when the user scrolls toward the start"
2551 );
2552 }
2553
2554 #[gpui::test]
2555 fn test_follow_tail_disengages_on_scrollbar_reposition(cx: &mut TestAppContext) {
2556 let cx = cx.add_empty_window();
2557
2558 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2560
2561 struct TestView(ListState);
2562 impl Render for TestView {
2563 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2564 list(self.0.clone(), |_, _, _| {
2565 div().h(px(50.)).w_full().into_any()
2566 })
2567 .w_full()
2568 .h_full()
2569 }
2570 }
2571
2572 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2573
2574 state.set_follow_mode(FollowMode::Tail);
2575
2576 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2578 view.clone().into_any_element()
2579 });
2580 assert!(state.is_following_tail());
2581
2582 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
2584
2585 let offset = state.logical_scroll_top();
2586 assert_eq!(offset.item_ix, 3);
2587 assert_eq!(offset.offset_in_item, px(0.));
2588 assert!(
2589 !state.is_following_tail(),
2590 "follow-tail should disengage when the scrollbar manually repositions the list"
2591 );
2592
2593 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2596 view.into_any_element()
2597 });
2598
2599 let offset = state.logical_scroll_top();
2600 assert_eq!(offset.item_ix, 3);
2601 assert_eq!(offset.offset_in_item, px(0.));
2602 }
2603
2604 #[gpui::test]
2605 fn test_scrollbar_drag_with_growing_content(cx: &mut TestAppContext) {
2606 let cx = cx.add_empty_window();
2607
2608 let last_item_height = Rc::new(Cell::new(50usize));
2609 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2610
2611 struct TestView {
2612 state: ListState,
2613 last_item_height: Rc<Cell<usize>>,
2614 }
2615 impl Render for TestView {
2616 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2617 let last_item_height = self.last_item_height.clone();
2618 list(self.state.clone(), move |index, _, _| {
2619 let height = if index == 9 {
2620 last_item_height.get()
2621 } else {
2622 50
2623 };
2624 div().h(px(height as f32)).w_full().into_any()
2625 })
2626 .w_full()
2627 .h_full()
2628 }
2629 }
2630
2631 let view = cx.update(|_, cx| {
2632 cx.new(|_| TestView {
2633 state: state.clone(),
2634 last_item_height: last_item_height.clone(),
2635 })
2636 });
2637
2638 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2639 view.clone().into_any_element()
2640 });
2641
2642 state.scrollbar_drag_started();
2643
2644 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
2645 let scrollbar_offset_before_growth = state.scroll_px_offset_for_scrollbar();
2646
2647 let offset = state.logical_scroll_top();
2648 assert_eq!(offset.item_ix, 3);
2649 assert_eq!(offset.offset_in_item, px(0.));
2650
2651 last_item_height.set(550);
2652 state.remeasure_items(9..10);
2653 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2654 view.clone().into_any_element()
2655 });
2656
2657 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2658 assert_eq!(
2659 state.scroll_px_offset_for_scrollbar(),
2660 scrollbar_offset_before_growth
2661 );
2662
2663 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
2664 let offset = state.logical_scroll_top();
2665 assert_eq!(offset.item_ix, 3);
2666 assert_eq!(offset.offset_in_item, px(0.));
2667 }
2668
2669 #[gpui::test]
2670 fn test_set_follow_tail_snaps_to_bottom(cx: &mut TestAppContext) {
2671 let cx = cx.add_empty_window();
2672
2673 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2675
2676 struct TestView(ListState);
2677 impl Render for TestView {
2678 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2679 list(self.0.clone(), |_, _, _| {
2680 div().h(px(50.)).w_full().into_any()
2681 })
2682 .w_full()
2683 .h_full()
2684 }
2685 }
2686
2687 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2688
2689 state.scroll_to(gpui::ListOffset {
2691 item_ix: 3,
2692 offset_in_item: px(0.),
2693 });
2694
2695 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2696 view.clone().into_any_element()
2697 });
2698
2699 let offset = state.logical_scroll_top();
2700 assert_eq!(offset.item_ix, 3);
2701 assert_eq!(offset.offset_in_item, px(0.));
2702 assert!(!state.is_following_tail());
2703
2704 state.set_follow_mode(FollowMode::Tail);
2707
2708 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2709 view.into_any_element()
2710 });
2711
2712 let offset = state.logical_scroll_top();
2715 assert_eq!(offset.item_ix, 6);
2716 assert_eq!(offset.offset_in_item, px(0.));
2717 assert!(state.is_following_tail());
2718 }
2719
2720 #[gpui::test]
2721 fn test_bottom_aligned_scrollbar_offset_at_end(cx: &mut TestAppContext) {
2722 let cx = cx.add_empty_window();
2723
2724 const ITEMS: usize = 10;
2725 const ITEM_SIZE: f32 = 50.0;
2726
2727 let state = ListState::new(
2728 ITEMS,
2729 crate::ListAlignment::Bottom,
2730 px(ITEMS as f32 * ITEM_SIZE),
2731 );
2732
2733 struct TestView(ListState);
2734 impl Render for TestView {
2735 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2736 list(self.0.clone(), |_, _, _| {
2737 div().h(px(ITEM_SIZE)).w_full().into_any()
2738 })
2739 .w_full()
2740 .h_full()
2741 }
2742 }
2743
2744 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
2745 cx.new(|_| TestView(state.clone())).into_any_element()
2746 });
2747
2748 assert_eq!(state.logical_scroll_top().item_ix, ITEMS);
2751
2752 let max_offset = state.max_offset_for_scrollbar();
2753 let scroll_offset = state.scroll_px_offset_for_scrollbar();
2754
2755 assert_eq!(
2756 -scroll_offset.y, max_offset.y,
2757 "scrollbar offset ({}) should equal max offset ({}) when list is pinned to bottom",
2758 -scroll_offset.y, max_offset.y,
2759 );
2760 }
2761
2762 #[gpui::test]
2766 fn test_follow_tail_reengages_when_scrolled_back_to_bottom(cx: &mut TestAppContext) {
2767 let cx = cx.add_empty_window();
2768
2769 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2771
2772 struct TestView(ListState);
2773 impl Render for TestView {
2774 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2775 list(self.0.clone(), |_, _, _| {
2776 div().h(px(50.)).w_full().into_any()
2777 })
2778 .w_full()
2779 .h_full()
2780 }
2781 }
2782
2783 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2784
2785 state.set_follow_mode(FollowMode::Tail);
2786
2787 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2788 view.clone().into_any_element()
2789 });
2790 assert!(state.is_following_tail());
2791
2792 cx.simulate_event(ScrollWheelEvent {
2794 position: point(px(50.), px(100.)),
2795 delta: ScrollDelta::Pixels(point(px(0.), px(50.))),
2796 ..Default::default()
2797 });
2798 assert!(!state.is_following_tail());
2799
2800 cx.simulate_event(ScrollWheelEvent {
2802 position: point(px(50.), px(100.)),
2803 delta: ScrollDelta::Pixels(point(px(0.), px(-10000.))),
2804 ..Default::default()
2805 });
2806
2807 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2810 view.clone().into_any_element()
2811 });
2812 assert!(
2813 state.is_following_tail(),
2814 "follow_tail should re-engage after scrolling back to the bottom"
2815 );
2816 }
2817
2818 #[gpui::test]
2821 fn test_follow_tail_reengagement_not_fooled_by_unmeasured_items(cx: &mut TestAppContext) {
2822 let cx = cx.add_empty_window();
2823
2824 let state = ListState::new(20, crate::ListAlignment::Top, px(1000.));
2828
2829 struct TestView(ListState);
2830 impl Render for TestView {
2831 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2832 list(self.0.clone(), |_, _, _| {
2833 div().h(px(50.)).w_full().into_any()
2834 })
2835 .w_full()
2836 .h_full()
2837 }
2838 }
2839
2840 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2841
2842 state.set_follow_mode(FollowMode::Tail);
2843
2844 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2845 view.clone().into_any_element()
2846 });
2847 assert!(state.is_following_tail());
2848
2849 cx.simulate_event(ScrollWheelEvent {
2853 position: point(px(50.), px(100.)),
2854 delta: ScrollDelta::Pixels(point(px(0.), px(200.))),
2855 ..Default::default()
2856 });
2857 assert!(!state.is_following_tail());
2858
2859 state.remeasure_items(19..20);
2863
2864 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2870 view.clone().into_any_element()
2871 });
2872 assert!(
2873 !state.is_following_tail(),
2874 "follow_tail should not falsely re-engage due to an unmeasured item \
2875 reducing items.summary().height"
2876 );
2877 }
2878
2879 #[gpui::test]
2880 fn test_follow_tail_reengages_after_scrollbar_disengagement(cx: &mut TestAppContext) {
2881 let cx = cx.add_empty_window();
2882
2883 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2885
2886 struct TestView(ListState);
2887 impl Render for TestView {
2888 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2889 list(self.0.clone(), |_, _, _| {
2890 div().h(px(50.)).w_full().into_any()
2891 })
2892 .w_full()
2893 .h_full()
2894 }
2895 }
2896
2897 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2898
2899 state.set_follow_mode(FollowMode::Tail);
2900 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2901 view.clone().into_any_element()
2902 });
2903 assert!(state.is_following_tail());
2904
2905 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
2907 assert!(!state.is_following_tail());
2908
2909 state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
2912 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2913 view.into_any_element()
2914 });
2915 assert!(
2916 state.is_following_tail(),
2917 "follow_tail should re-engage after scrolling back to the bottom via the scrollbar"
2918 );
2919 }
2920
2921 #[gpui::test]
2922 fn test_follow_tail_reengages_after_scrollbar_drag_to_bottom_while_growing(
2923 cx: &mut TestAppContext,
2924 ) {
2925 let cx = cx.add_empty_window();
2926
2927 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2928
2929 struct TestView(ListState);
2930 impl Render for TestView {
2931 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2932 list(self.0.clone(), |_, _, _| {
2933 div().h(px(50.)).w_full().into_any()
2934 })
2935 .w_full()
2936 .h_full()
2937 }
2938 }
2939
2940 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2941
2942 state.set_follow_mode(FollowMode::Tail);
2943 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2944 view.clone().into_any_element()
2945 });
2946 assert!(state.is_following_tail());
2947
2948 state.scrollbar_drag_started();
2949
2950 state.splice(10..10, 10);
2951 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2952 view.clone().into_any_element()
2953 });
2954
2955 state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
2956 state.scrollbar_drag_ended();
2957
2958 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2959 view.into_any_element()
2960 });
2961
2962 assert!(
2963 state.is_following_tail(),
2964 "follow_tail should re-engage when the user drags the scrollbar to \
2965 the bottom of its track, even when content has grown during the drag \
2966 (so frozen_bottom < live_bottom)"
2967 );
2968 }
2969}