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