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