1use crate::{
12 AnyElement, App, AvailableSpace, Bounds, ContentMask, DispatchPhase, Edges, Element, EntityId,
13 FocusHandle, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, IntoElement,
14 Overflow, Pixels, Point, ScrollDelta, ScrollEvent, Size, Style, StyleRefinement, Styled,
15 Window, point, px, size,
16};
17use collections::VecDeque;
18use refineable::Refineable as _;
19use std::{cell::RefCell, ops::Range, rc::Rc};
20use sum_tree::{Bias, Dimensions, SumTree};
21
22pub(crate) type RenderItemFn = dyn FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static;
23
24pub fn list(
26 state: ListState,
27 render_item: impl FnMut(usize, &mut Window, &mut App) -> AnyElement + 'static,
28) -> List {
29 crate::fast::layers::invalidate::note_list_built();
30 List {
31 state,
32 render_item: crate::fast::layers::lists::spanned_render_item(render_item),
33 style: StyleRefinement::default(),
34 sizing_behavior: ListSizingBehavior::default(),
35 }
36}
37
38pub struct List {
40 state: ListState,
41 render_item: Box<RenderItemFn>,
42 style: StyleRefinement,
43 sizing_behavior: ListSizingBehavior,
44}
45
46impl List {
47 pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
49 self.sizing_behavior = behavior;
50 self
51 }
52}
53
54#[derive(Clone)]
56pub struct ListState(pub(crate) Rc<RefCell<StateInner>>);
57
58impl std::fmt::Debug for ListState {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 f.write_str("ListState")
61 }
62}
63
64pub(crate) struct StateInner {
65 pub(crate) last_layout_bounds: Option<Bounds<Pixels>>,
66 pub(crate) last_padding: Option<Edges<Pixels>>,
67 pub(crate) items: SumTree<ListItem>,
68 pub(crate) scroll_anchor: Option<ScrollAnchor>,
69 alignment: ListAlignment,
70 overdraw: Pixels,
71 reset: bool,
72 #[allow(clippy::type_complexity)]
73 scroll_handler: Option<Box<dyn FnMut(&ListScrollEvent, &mut Window, &mut App)>>,
74 scrollbar_drag_start_height: Option<Pixels>,
75 measuring_behavior: ListMeasuringBehavior,
76 item_measurement_ready: Option<Box<dyn Fn(usize, &App) -> bool>>,
77 pub(crate) follow_state: FollowState,
78 pub(crate) version: crate::fast::dependencies::StateVersion,
79}
80
81#[derive(Clone, Copy)]
82pub(crate) struct ScrollAnchor {
83 pub(crate) position: ListOffset,
84 pub(crate) pending: Option<PendingScroll>,
85 pub(crate) provisional: bool,
86 pub(crate) pending_end: bool,
87}
88
89#[derive(Clone, Copy)]
90pub(crate) enum PendingScroll {
91 Absolute(Pixels),
92 Proportional(f32),
93}
94
95enum ScrollAnchorMode {
96 Absolute,
97 Proportional,
98}
99
100#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
102pub enum FollowMode {
103 #[default]
105 Normal,
106 Tail,
108}
109
110#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
111pub(crate) enum FollowState {
112 #[default]
113 Normal,
114 Tail {
115 is_following: bool,
116 },
117}
118
119impl FollowState {
120 fn is_following(&self) -> bool {
121 matches!(self, FollowState::Tail { is_following: true })
122 }
123
124 fn has_stopped_following(&self) -> bool {
125 matches!(
126 self,
127 FollowState::Tail {
128 is_following: false
129 }
130 )
131 }
132
133 fn start_following(&mut self) {
134 if let FollowState::Tail {
135 is_following: false,
136 } = self
137 {
138 *self = FollowState::Tail { is_following: true };
139 }
140 }
141
142 fn stop_following(&mut self) {
143 if let FollowState::Tail { is_following: true } = self {
144 *self = FollowState::Tail {
145 is_following: false,
146 };
147 }
148 }
149}
150
151#[derive(Clone, Copy, Debug, Eq, PartialEq)]
153pub enum ListAlignment {
154 Top,
156 Bottom,
158}
159
160pub struct ListScrollEvent {
162 pub visible_range: Range<usize>,
164
165 pub count: usize,
167
168 pub is_scrolled: bool,
170
171 pub is_following_tail: bool,
173}
174
175#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
177pub enum ListSizingBehavior {
178 Infer,
180 #[default]
182 Auto,
183}
184
185#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
187pub enum ListMeasuringBehavior {
188 Measure(bool),
191 #[default]
193 Visible,
194}
195
196impl ListMeasuringBehavior {
197 fn reset(&mut self) {
198 match self {
199 ListMeasuringBehavior::Measure(has_measured) => *has_measured = false,
200 ListMeasuringBehavior::Visible => {}
201 }
202 }
203}
204
205#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
207pub enum ListHorizontalSizingBehavior {
208 #[default]
210 FitList,
211 Unconstrained,
213}
214
215struct LayoutItemsResponse {
216 max_item_width: Pixels,
217 scroll_top: ListOffset,
218 item_layouts: VecDeque<ItemLayout>,
219}
220
221struct ItemLayout {
222 index: usize,
223 element: AnyElement,
224 size: Size<Pixels>,
225}
226
227pub struct ListPrepaintState {
229 hitbox: Hitbox,
230 layout: LayoutItemsResponse,
231}
232
233#[derive(Clone)]
234pub(crate) enum ListItem {
235 Unmeasured {
236 size_hint: Option<Size<Pixels>>,
237 focus_handle: Option<FocusHandle>,
238 },
239 Measured {
240 size: Size<Pixels>,
241 focus_handle: Option<FocusHandle>,
242 },
243}
244
245impl ListItem {
246 fn with_measurement(&self, size: Size<Pixels>, ready: bool) -> Self {
247 if ready {
248 Self::Measured {
249 size,
250 focus_handle: self.focus_handle(),
251 }
252 } else {
253 Self::Unmeasured {
254 size_hint: Some(size),
255 focus_handle: self.focus_handle(),
256 }
257 }
258 }
259
260 pub(crate) fn size(&self) -> Option<Size<Pixels>> {
261 if let ListItem::Measured { size, .. } = self {
262 Some(*size)
263 } else {
264 None
265 }
266 }
267
268 fn size_hint(&self) -> Option<Size<Pixels>> {
269 match self {
270 ListItem::Measured { size, .. } => Some(*size),
271 ListItem::Unmeasured { size_hint, .. } => *size_hint,
272 }
273 }
274
275 fn focus_handle(&self) -> Option<FocusHandle> {
276 match self {
277 ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
278 focus_handle.clone()
279 }
280 }
281 }
282
283 fn contains_focused(&self, window: &Window, cx: &App) -> bool {
284 match self {
285 ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
286 focus_handle
287 .as_ref()
288 .is_some_and(|handle| handle.contains_focused(window, cx))
289 }
290 }
291 }
292}
293
294#[derive(Clone, Debug, Default, PartialEq)]
295pub(crate) struct ListItemSummary {
296 pub(crate) count: usize,
297 rendered_count: usize,
298 unrendered_count: usize,
299 pub(crate) height: Pixels,
300 has_focus_handles: bool,
301 pub(crate) has_unknown_height: bool,
302}
303
304#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
305pub(crate) struct Count(pub(crate) usize);
306
307#[derive(Clone, Debug, Default)]
308struct Height(Pixels);
309
310impl ListState {
311 pub fn new(item_count: usize, alignment: ListAlignment, overdraw: Pixels) -> Self {
318 let state = Self(Rc::new(RefCell::new(StateInner {
319 last_layout_bounds: None,
320 last_padding: None,
321 items: SumTree::default(),
322 scroll_anchor: None,
323 alignment,
324 overdraw,
325 scroll_handler: None,
326 reset: false,
327 scrollbar_drag_start_height: None,
328 measuring_behavior: ListMeasuringBehavior::default(),
329 item_measurement_ready: None,
330 follow_state: FollowState::default(),
331 version: crate::fast::dependencies::StateVersion::default(),
332 })));
333 state.splice(0..0, item_count);
334 state
335 }
336
337 pub fn measure_all(self) -> Self {
341 self.0.borrow_mut().measuring_behavior = ListMeasuringBehavior::Measure(false);
342 self
343 }
344
345 pub fn with_uniform_item_height(self, height: Pixels) -> Self {
352 self.apply_uniform_item_height(height);
353 self
354 }
355
356 pub fn reset(&self, element_count: usize) {
360 let old_count = {
361 let state = &mut *self.0.borrow_mut();
362 crate::fast::dependencies::StateVersion::bump(&state.version);
363 state.reset = true;
364 state.measuring_behavior.reset();
365 state.set_scroll_anchor(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, ScrollAnchorMode::Proportional);
408 }
409
410 pub fn remeasure_items(&self, range: Range<usize>) {
418 self.remeasure_items_with_scroll_anchor(range, ScrollAnchorMode::Absolute);
419 }
420
421 fn remeasure_items_with_scroll_anchor(&self, range: Range<usize>, mode: ScrollAnchorMode) {
422 let state = &mut *self.0.borrow_mut();
423 crate::fast::dependencies::StateVersion::bump(&state.version);
424
425 if let Some(anchor) = state.scroll_anchor.as_mut()
426 && range.contains(&anchor.position.item_ix)
427 {
428 anchor.pending = match mode {
429 ScrollAnchorMode::Absolute => {
430 Some(PendingScroll::Absolute(anchor.position.offset_in_item))
431 }
432 ScrollAnchorMode::Proportional => {
433 let mut cursor = state.items.cursor::<Count>(());
434 cursor.seek(&Count(anchor.position.item_ix), Bias::Right);
435 cursor
436 .item()
437 .and_then(|item| item.size())
438 .map(|size| {
439 let fraction = if size.height > px(0.) {
440 (anchor.position.offset_in_item / size.height).clamp(0., 1.)
441 } else {
442 0.
443 };
444 PendingScroll::Proportional(fraction)
445 })
446 .or(anchor.pending)
447 }
448 };
449 }
450
451 let new_items = {
454 let mut cursor = state.items.cursor::<Count>(());
455 let mut new_items = cursor.slice(&Count(range.start), Bias::Right);
456 let invalidated = cursor.slice(&Count(range.end), Bias::Right);
457 new_items.extend(
458 invalidated.iter().map(|item| ListItem::Unmeasured {
459 size_hint: item.size_hint(),
460 focus_handle: item.focus_handle(),
461 }),
462 (),
463 );
464 new_items.append(cursor.suffix(), ());
465 new_items
466 };
467 state.items = new_items;
468 state.measuring_behavior.reset();
469 }
470
471 pub fn item_count(&self) -> usize {
473 self.0.borrow().items.summary().count
474 }
475
476 pub fn is_scrolled_to_end(&self) -> Option<bool> {
479 let state = self.0.borrow();
480 crate::fast::layers::lists::note_at_end_read(&state);
481 let bounds = state.last_layout_bounds?;
482 let summary = state.items.summary();
483 if summary.has_unknown_height {
484 return None;
485 }
486 let padding = state.last_padding.unwrap_or_default();
487 let content_height = summary.height + padding.top + padding.bottom;
488 let scroll_max = (content_height - bounds.size.height).max(px(0.));
489 if scroll_max <= px(0.) {
490 return None;
491 }
492 let scroll_top = state.scroll_top(&state.logical_scroll_top());
493 Some(scroll_top >= scroll_max)
494 }
495
496 pub fn splice(&self, old_range: Range<usize>, count: usize) {
499 self.splice_focusable(old_range, (0..count).map(|_| None))
500 }
501
502 pub fn splice_focusable(
507 &self,
508 old_range: Range<usize>,
509 focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
510 ) {
511 let state = &mut *self.0.borrow_mut();
512 crate::fast::dependencies::StateVersion::bump(&state.version);
513
514 let mut old_items = state.items.cursor::<Count>(());
515 let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right);
516 old_items.seek_forward(&Count(old_range.end), Bias::Right);
517
518 let mut spliced_count = 0;
519 new_items.extend(
520 focus_handles.into_iter().map(|focus_handle| {
521 spliced_count += 1;
522 ListItem::Unmeasured {
523 size_hint: None,
524 focus_handle,
525 }
526 }),
527 (),
528 );
529 new_items.append(old_items.suffix(), ());
530 drop(old_items);
531 state.items = new_items;
532
533 if let Some(anchor) = state.scroll_anchor.as_mut() {
534 if anchor.provisional && old_range.start <= anchor.position.item_ix {
535 anchor.provisional = false;
536 anchor.pending = None;
537 }
538 if old_range.contains(&anchor.position.item_ix) {
539 anchor.position = ListOffset {
540 item_ix: old_range.start,
541 offset_in_item: px(0.),
542 };
543 anchor.pending = None;
544 } else if old_range.end <= anchor.position.item_ix {
545 anchor.position.item_ix = anchor.position.item_ix - old_range.len() + spliced_count;
546 }
547 }
548 }
549
550 pub fn set_scroll_handler(
552 &self,
553 handler: impl FnMut(&ListScrollEvent, &mut Window, &mut App) + 'static,
554 ) {
555 self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
556 }
557
558 pub fn logical_scroll_top(&self) -> ListOffset {
560 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
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 crate::fast::dependencies::StateVersion::bump(&state.version);
573
574 if distance < px(0.) {
575 state.follow_state.stop_following();
576 }
577
578 let mut cursor = state.items.cursor::<ListItemSummary>(());
579 cursor.seek(&Count(current_offset.item_ix), Bias::Right);
580
581 let start_pixel_offset = cursor.start().height + current_offset.offset_in_item;
582 let new_pixel_offset = (start_pixel_offset + distance).max(px(0.));
583 if new_pixel_offset > start_pixel_offset {
584 cursor.seek_forward(&Height(new_pixel_offset), Bias::Right);
585 } else {
586 cursor.seek(&Height(new_pixel_offset), Bias::Right);
587 }
588
589 let scroll_top = ListOffset {
590 item_ix: cursor.start().count,
591 offset_in_item: new_pixel_offset - cursor.start().height,
592 };
593 drop(cursor);
594 state.set_scroll_anchor(Some(scroll_top));
595 }
596
597 pub fn scroll_to_end(&self) {
604 let state = &mut *self.0.borrow_mut();
605 crate::fast::layers::lists::note_scrolled_to_end(state);
606 let item_count = state.items.summary().count;
607 state.set_scroll_anchor(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 if mode == FollowMode::Normal {
619 self.pause_following_tail();
620 }
621 let state = &mut *self.0.borrow_mut();
622 crate::fast::dependencies::StateVersion::bump(&state.version);
623
624 match mode {
625 FollowMode::Normal => {
626 state.follow_state = FollowState::Normal;
627 }
628 FollowMode::Tail => {
629 state.follow_state = FollowState::Tail { is_following: true };
630 if matches!(mode, FollowMode::Tail) {
631 let item_count = state.items.summary().count;
632 state.set_scroll_anchor(Some(ListOffset {
633 item_ix: item_count,
634 offset_in_item: px(0.),
635 }));
636 }
637 }
638 }
639 }
640
641 pub fn pause_following_tail(&self) {
651 crate::fast::dependencies::note_list_following_paused(&self.0.borrow());
652 let state = &mut *self.0.borrow_mut();
653 if state.follow_state.is_following()
654 && let Some(anchor) = state.scroll_anchor.as_mut()
655 {
656 anchor.pending_end = false;
657 }
658 state.follow_state.stop_following();
659 }
660
661 pub fn set_item_measurement_readiness(&self, ready: impl Fn(usize, &App) -> bool + 'static) {
665 self.0.borrow_mut().item_measurement_ready = Some(Box::new(ready));
666 }
667
668 pub fn is_following_tail(&self) -> bool {
671 matches!(
672 self.0.borrow().follow_state,
673 FollowState::Tail { is_following: true }
674 )
675 }
676
677 pub fn scroll_to(&self, mut scroll_top: ListOffset) {
679 let state = &mut *self.0.borrow_mut();
680 let scroll_start = crate::fast::dependencies::ListScrollStart::of(state);
681 let item_count = state.items.summary().count;
682 if scroll_top.item_ix >= item_count {
683 scroll_top.item_ix = item_count;
684 scroll_top.offset_in_item = px(0.);
685 }
686
687 if scroll_top.item_ix < item_count {
688 state.follow_state.stop_following();
689 }
690
691 crate::fast::dependencies::ListScrollStart::note_scrolled(scroll_start, state, &scroll_top);
692 state.set_scroll_anchor(Some(scroll_top));
693 }
694
695 pub fn scroll_to_reveal_item(&self, ix: usize) {
697 let state = &mut *self.0.borrow_mut();
698 crate::fast::dependencies::StateVersion::bump(&state.version);
699
700 let mut scroll_top = state.logical_scroll_top();
701 let height = state
702 .last_layout_bounds
703 .map_or(px(0.), |bounds| bounds.size.height);
704 let padding = state.last_padding.unwrap_or_default();
705
706 if ix <= scroll_top.item_ix {
707 scroll_top.item_ix = ix;
708 scroll_top.offset_in_item = px(0.);
709 } else {
710 let mut cursor = state.items.cursor::<ListItemSummary>(());
711 cursor.seek(&Count(ix + 1), Bias::Right);
712 let bottom = cursor.start().height + padding.top;
713 let goal_top = px(0.).max(bottom - height + padding.bottom);
714
715 cursor.seek(&Height(goal_top), Bias::Left);
716 let start_ix = cursor.start().count;
717 let start_item_top = cursor.start().height;
718
719 if start_ix >= scroll_top.item_ix {
720 scroll_top.item_ix = start_ix;
721 scroll_top.offset_in_item = goal_top - start_item_top;
722 }
723 }
724
725 state.set_scroll_anchor(Some(scroll_top));
726 }
727
728 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
731 let state = &*self.0.borrow();
732 crate::fast::layers::invalidate::note_offset_read(&state.version);
733
734 let bounds = state.last_layout_bounds.unwrap_or_default();
735 let scroll_top = state.logical_scroll_top();
736 if ix < scroll_top.item_ix {
737 return None;
738 }
739
740 let mut cursor = state.items.cursor::<Dimensions<Count, Height>>(());
741 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
742
743 let scroll_top = cursor.start().1.0 + scroll_top.offset_in_item;
744
745 cursor.seek_forward(&Count(ix), Bias::Right);
746 if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
747 let &Dimensions(Count(count), Height(top), _) = cursor.start();
748 if count == ix {
749 let top = bounds.top() + top - scroll_top;
750 return Some(Bounds::from_corners(
751 point(bounds.left(), top),
752 point(bounds.right(), top + size.height),
753 ));
754 }
755 }
756 None
757 }
758
759 pub fn scrollbar_drag_started(&self) {
764 let mut state = self.0.borrow_mut();
765 crate::fast::dependencies::StateVersion::bump(&state.version);
766 state.scrollbar_drag_start_height = Some(state.items.summary().height);
767 }
768
769 pub fn scrollbar_drag_ended(&self) {
773 crate::fast::dependencies::StateVersion::bump(&self.0.borrow().version);
774 self.0.borrow_mut().scrollbar_drag_start_height.take();
775 }
776
777 pub fn is_scrollbar_dragging(&self) -> bool {
784 self.0.borrow().scrollbar_drag_start_height.is_some()
785 }
786
787 pub fn set_offset_from_scrollbar(&self, point: Point<Pixels>) {
789 crate::fast::layers::invalidate::list_offset_set(&self.0.borrow().version);
790 self.0.borrow_mut().set_offset_from_scrollbar(point);
791 }
792
793 pub fn max_offset_for_scrollbar(&self) -> Point<Pixels> {
796 let state = self.0.borrow();
797 point(Pixels::ZERO, state.max_scroll_offset())
798 }
799
800 pub fn scroll_px_offset_for_scrollbar(&self) -> Point<Pixels> {
805 let state = &self.0.borrow();
806 crate::fast::layers::invalidate::note_offset_read(&state.version);
807
808 if state.scroll_anchor.is_none() && state.alignment == ListAlignment::Bottom {
809 return Point::new(px(0.), -state.max_scroll_offset());
810 }
811
812 let logical_scroll_top = state.logical_scroll_top();
813
814 let mut cursor = state.items.cursor::<ListItemSummary>(());
815 let summary: ListItemSummary =
816 cursor.summary(&Count(logical_scroll_top.item_ix), Bias::Right);
817 let offset = summary.height + logical_scroll_top.offset_in_item;
818
819 Point::new(px(0.), -offset)
820 }
821
822 pub fn viewport_bounds(&self) -> Bounds<Pixels> {
824 self.0.borrow().last_layout_bounds.unwrap_or_default()
825 }
826
827 pub fn item_is_above_viewport(&self, ix: usize) -> Option<bool> {
835 let viewport_bounds = self.0.borrow().last_layout_bounds?;
836
837 let scroll_top = self.logical_scroll_top();
838 if ix < scroll_top.item_ix {
839 return Some(true);
842 }
843
844 let item_bounds = self.bounds_for_item(ix)?;
845 Some(item_bounds.bottom() <= viewport_bounds.top())
846 }
847
848 pub fn item_is_below_viewport(&self, ix: usize) -> Option<bool> {
854 let viewport_bounds = self.0.borrow().last_layout_bounds?;
855
856 let scroll_top = self.logical_scroll_top();
857 if ix < scroll_top.item_ix {
858 return Some(false);
861 }
862
863 let item_bounds = self.bounds_for_item(ix)?;
864 Some(item_bounds.top() >= viewport_bounds.bottom())
865 }
866}
867
868impl StateInner {
869 fn max_scroll_offset(&self) -> Pixels {
870 let bounds = self.last_layout_bounds.unwrap_or_default();
871 let height = self
872 .scrollbar_drag_start_height
873 .unwrap_or_else(|| self.items.summary().height);
874 (height - bounds.size.height).max(px(0.))
875 }
876
877 fn visible_range(
878 items: &SumTree<ListItem>,
879 height: Pixels,
880 scroll_top: &ListOffset,
881 ) -> Range<usize> {
882 let mut cursor = items.cursor::<ListItemSummary>(());
883 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
884 let start_y = cursor.start().height + scroll_top.offset_in_item;
885 cursor.seek_forward(&Height(start_y + height), Bias::Left);
886 scroll_top.item_ix..cursor.start().count + 1
887 }
888
889 fn scroll(
890 &mut self,
891 scroll_top: &ListOffset,
892 height: Pixels,
893 delta: Point<Pixels>,
894 current_view: EntityId,
895 window: &mut Window,
896 cx: &mut App,
897 ) {
898 if self.reset || delta.y == px(0.) {
901 return;
902 }
903
904 let padding = self.last_padding.unwrap_or_default();
905 let scroll_max =
906 (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
907 let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
908 .max(px(0.))
909 .min(scroll_max);
910
911 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
912 self.set_scroll_anchor(None);
913 } else {
914 let (start, ..) =
915 self.items
916 .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
917 let scroll_top = ListOffset {
918 item_ix: start.count,
919 offset_in_item: new_scroll_top - start.height,
920 };
921 self.set_scroll_anchor(Some(scroll_top));
922 }
923
924 if delta.y > px(0.) {
925 self.follow_state.stop_following();
926 }
927
928 if let Some(handler) = self.scroll_handler.as_mut() {
929 let visible_range = Self::visible_range(&self.items, height, scroll_top);
930 handler(
931 &ListScrollEvent {
932 visible_range,
933 count: self.items.summary().count,
934 is_scrolled: self.scroll_anchor.is_some(),
935 is_following_tail: matches!(
936 self.follow_state,
937 FollowState::Tail { is_following: true }
938 ),
939 },
940 window,
941 cx,
942 );
943 }
944
945 crate::fast::layers::invalidate::note_list_scrolled(window, &self.version, current_view);
946 cx.notify(current_view);
947 }
948
949 pub(crate) fn logical_scroll_top(&self) -> ListOffset {
950 self.scroll_anchor
951 .map(|anchor| anchor.position)
952 .unwrap_or_else(|| match self.alignment {
953 ListAlignment::Top => ListOffset {
954 item_ix: 0,
955 offset_in_item: px(0.),
956 },
957 ListAlignment::Bottom => ListOffset {
958 item_ix: self.items.summary().count,
959 offset_in_item: px(0.),
960 },
961 })
962 }
963
964 pub(crate) fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
965 let (start, ..) = self.items.find::<ListItemSummary, _>(
966 (),
967 &Count(logical_scroll_top.item_ix),
968 Bias::Right,
969 );
970 start.height + logical_scroll_top.offset_in_item
971 }
972
973 fn is_item_ready(&self, index: usize, cx: &App) -> bool {
974 self.item_measurement_ready
975 .as_ref()
976 .is_none_or(|ready| ready(index, cx))
977 }
978
979 fn is_provisional(&self) -> bool {
980 self.scroll_anchor.is_some_and(|anchor| anchor.provisional)
981 }
982
983 fn set_scroll_anchor(&mut self, position: Option<ListOffset>) {
984 let Some(position) = position else {
985 self.scroll_anchor = None;
986 return;
987 };
988 let pending = self
989 .scroll_anchor
990 .and_then(|anchor| anchor.pending)
991 .filter(|_| position.item_ix < self.items.summary().count)
992 .and_then(|pending| match (pending, self.is_provisional()) {
993 (PendingScroll::Absolute(_), _) | (_, true) => {
994 Some(PendingScroll::Absolute(position.offset_in_item))
995 }
996 (PendingScroll::Proportional(_), false) => {
997 let mut cursor = self.items.cursor::<Count>(());
998 cursor.seek(&Count(position.item_ix), Bias::Right);
999 cursor
1000 .item()
1001 .and_then(|item| item.size_hint())
1002 .filter(|size| size.height > px(0.))
1003 .map(|size| {
1004 PendingScroll::Proportional(
1005 (position.offset_in_item / size.height).clamp(0., 1.),
1006 )
1007 })
1008 }
1009 });
1010 self.scroll_anchor = Some(ScrollAnchor {
1011 position,
1012 pending,
1013 provisional: false,
1014 pending_end: false,
1015 });
1016 }
1017
1018 fn layout_all_items(
1019 &mut self,
1020 available_width: Pixels,
1021 render_item: &mut RenderItemFn,
1022 window: &mut Window,
1023 cx: &mut App,
1024 ) {
1025 match &mut self.measuring_behavior {
1026 ListMeasuringBehavior::Visible => {
1027 return;
1028 }
1029 ListMeasuringBehavior::Measure(has_measured) => {
1030 if *has_measured {
1031 return;
1032 }
1033 *has_measured = true;
1034 }
1035 }
1036
1037 let mut cursor = self.items.cursor::<Count>(());
1038 let available_item_space = size(
1039 AvailableSpace::Definite(available_width),
1040 AvailableSpace::MinContent,
1041 );
1042
1043 let mut measured_items = Vec::default();
1044
1045 for (ix, item) in cursor.enumerate() {
1046 let size = item.size().unwrap_or_else(|| {
1047 let mut element = render_item(ix, window, cx);
1048 crate::fast::layout_key::layout_as_list_item(
1049 &mut element,
1050 ix,
1051 available_item_space,
1052 window,
1053 cx,
1054 )
1055 });
1056
1057 measured_items.push(item.with_measurement(size, self.is_item_ready(ix, cx)));
1058 }
1059
1060 self.items = SumTree::from_iter(measured_items, ());
1061 self.measuring_behavior =
1062 ListMeasuringBehavior::Measure(self.items.summary().unrendered_count == 0);
1063 }
1064
1065 fn layout_items(
1066 &mut self,
1067 available_width: Option<Pixels>,
1068 available_height: Pixels,
1069 padding: &Edges<Pixels>,
1070 render_item: &mut RenderItemFn,
1071 window: &mut Window,
1072 cx: &mut App,
1073 ) -> LayoutItemsResponse {
1074 let old_items = self.items.clone();
1075 let mut measured_items = VecDeque::new();
1076 let mut item_layouts = VecDeque::new();
1077 let mut rendered_height = padding.top;
1078 let mut max_item_width = px(0.);
1079 let mut scroll_top = self.logical_scroll_top();
1080
1081 if self.follow_state.is_following()
1082 || self.scroll_anchor.is_some_and(|anchor| anchor.pending_end)
1083 {
1084 scroll_top = ListOffset {
1085 item_ix: self.items.summary().count,
1086 offset_in_item: px(0.),
1087 };
1088 self.set_scroll_anchor(Some(scroll_top));
1089 }
1090
1091 let preserve_anchor = scroll_top.item_ix < self.items.summary().count;
1092 if !preserve_anchor {
1093 self.follow_state.start_following();
1094 }
1095 let mut provisional = false;
1096 let mut rendered_focused_item = false;
1097
1098 let available_item_space = size(
1099 available_width.map_or(AvailableSpace::MaxContent, |width| {
1100 AvailableSpace::Definite(width)
1101 }),
1102 AvailableSpace::MinContent,
1103 );
1104
1105 let mut cursor = old_items.cursor::<Count>(());
1106
1107 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1109 for (ix, item) in cursor.by_ref().enumerate() {
1110 let visible_height = rendered_height - scroll_top.offset_in_item;
1111 if visible_height >= available_height + self.overdraw {
1112 break;
1113 }
1114
1115 let item_index = scroll_top.item_ix + ix;
1116 let (size, ready) = if (visible_height >= available_height
1117 || crate::fast::layers::lists::keeps_row(
1118 window,
1119 &self.version,
1120 item_index,
1121 item.size().is_some(),
1122 ))
1123 && let Some(size) = item.size()
1124 {
1125 (size, self.is_item_ready(item_index, cx))
1126 } else {
1127 let mut element = render_item(item_index, window, cx);
1128 let element_size = crate::fast::layout_key::layout_as_list_item(
1129 &mut element,
1130 item_index,
1131 available_item_space,
1132 window,
1133 cx,
1134 );
1135 let ready = self.is_item_ready(item_index, cx);
1136 if ix == 0
1137 && ready
1138 && let Some(anchor) = self.scroll_anchor.as_mut()
1139 && let Some(pending) = anchor.pending.take()
1140 {
1141 scroll_top.offset_in_item = match pending {
1142 PendingScroll::Absolute(offset) => offset.min(element_size.height),
1143 PendingScroll::Proportional(fraction) => element_size.height * fraction,
1144 };
1145 anchor.position = scroll_top;
1146 }
1147
1148 if visible_height < available_height {
1149 item_layouts.push_back(ItemLayout {
1150 index: item_index,
1151 element,
1152 size: element_size,
1153 });
1154 if item.contains_focused(window, cx) {
1155 rendered_focused_item = true;
1156 }
1157 }
1158 (element_size, ready)
1159 };
1160
1161 rendered_height += size.height;
1162 max_item_width = max_item_width.max(size.width);
1163 provisional |= !ready;
1164 measured_items.push_back(item.with_measurement(size, ready));
1165 if !ready && visible_height >= available_height {
1166 break;
1167 }
1168 }
1169 rendered_height += padding.bottom;
1170
1171 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1173
1174 if !provisional && rendered_height - scroll_top.offset_in_item < available_height {
1177 let forward_layout_count = item_layouts.len();
1178 let forward_focused = rendered_focused_item;
1179 while rendered_height < available_height {
1180 cursor.prev();
1181 if let Some(item) = cursor.item() {
1182 let item_index = cursor.start().0;
1183 let mut element = render_item(item_index, window, cx);
1184 let element_size = crate::fast::layout_key::layout_as_list_item(
1185 &mut element,
1186 item_index,
1187 available_item_space,
1188 window,
1189 cx,
1190 );
1191 let ready = self.is_item_ready(item_index, cx);
1192 provisional |= !ready;
1193 rendered_height += element_size.height;
1194 measured_items.push_front(item.with_measurement(element_size, ready));
1195 item_layouts.push_front(ItemLayout {
1196 index: item_index,
1197 element,
1198 size: element_size,
1199 });
1200 if item.contains_focused(window, cx) {
1201 rendered_focused_item = true;
1202 }
1203 if preserve_anchor && provisional {
1204 break;
1205 }
1206 } else {
1207 break;
1208 }
1209 }
1210
1211 if preserve_anchor && provisional {
1212 item_layouts.drain(..item_layouts.len() - forward_layout_count);
1213 rendered_focused_item = forward_focused;
1214 } else {
1215 scroll_top = ListOffset {
1216 item_ix: cursor.start().0,
1217 offset_in_item: rendered_height - available_height,
1218 };
1219
1220 match self.alignment {
1221 ListAlignment::Top => {
1222 scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
1223 self.set_scroll_anchor(Some(scroll_top));
1224 }
1225 ListAlignment::Bottom => {
1226 scroll_top = ListOffset {
1227 item_ix: cursor.start().0,
1228 offset_in_item: rendered_height - available_height,
1229 };
1230 self.set_scroll_anchor(None);
1231 }
1232 };
1233 }
1234 }
1235
1236 if let Some(anchor) = self.scroll_anchor.as_mut() {
1237 anchor.provisional = preserve_anchor && provisional;
1238 anchor.pending_end = !preserve_anchor && provisional;
1239 }
1240
1241 if !provisional {
1243 let mut leading_overdraw = scroll_top.offset_in_item;
1244 while leading_overdraw < self.overdraw {
1245 cursor.prev();
1246 if let Some(item) = cursor.item() {
1247 let size = if let ListItem::Measured { size, .. } = item {
1248 *size
1249 } else {
1250 let mut element = render_item(cursor.start().0, window, cx);
1251 crate::fast::layout_key::layout_as_list_item(
1252 &mut element,
1253 cursor.start().0,
1254 available_item_space,
1255 window,
1256 cx,
1257 )
1258 };
1259
1260 leading_overdraw += size.height;
1261 let ready = self.is_item_ready(cursor.start().0, cx);
1262 measured_items.push_front(item.with_measurement(size, ready));
1263 if !ready {
1264 break;
1265 }
1266 } else {
1267 break;
1268 }
1269 }
1270 }
1271
1272 let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
1273 let mut cursor = old_items.cursor::<Count>(());
1274 let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right);
1275 new_items.extend(measured_items, ());
1276 cursor.seek(&Count(measured_range.end), Bias::Right);
1277 new_items.append(cursor.suffix(), ());
1278 self.items = new_items;
1279
1280 if !provisional && self.follow_state.has_stopped_following() {
1284 let padding = self.last_padding.unwrap_or_default();
1285 let total_height = self.items.summary().height + padding.top + padding.bottom;
1286 let scroll_offset = self.scroll_top(&scroll_top);
1287 if scroll_offset + available_height >= total_height - px(1.0) {
1288 self.follow_state.start_following();
1289 }
1290 }
1291
1292 if !rendered_focused_item {
1296 let mut cursor = self
1297 .items
1298 .filter::<_, Count>((), |summary| summary.has_focus_handles);
1299 cursor.next();
1300 while let Some(item) = cursor.item() {
1301 if item.contains_focused(window, cx) {
1302 let item_index = cursor.start().0;
1303 let mut element = render_item(cursor.start().0, window, cx);
1304 let size = crate::fast::layout_key::layout_as_list_item(
1305 &mut element,
1306 item_index,
1307 available_item_space,
1308 window,
1309 cx,
1310 );
1311 item_layouts.push_back(ItemLayout {
1312 index: item_index,
1313 element,
1314 size,
1315 });
1316 break;
1317 }
1318 cursor.next();
1319 }
1320 }
1321
1322 LayoutItemsResponse {
1323 max_item_width,
1324 scroll_top,
1325 item_layouts,
1326 }
1327 }
1328
1329 fn prepaint_items(
1330 &mut self,
1331 bounds: Bounds<Pixels>,
1332 padding: Edges<Pixels>,
1333 autoscroll: bool,
1334 render_item: &mut RenderItemFn,
1335 window: &mut Window,
1336 cx: &mut App,
1337 ) -> Result<LayoutItemsResponse, ListOffset> {
1338 window.transact(|window| {
1339 match self.measuring_behavior {
1340 ListMeasuringBehavior::Measure(has_measured) if !has_measured => {
1341 self.layout_all_items(bounds.size.width, render_item, window, cx);
1342 }
1343 _ => {}
1344 }
1345
1346 let mut layout_response = self.layout_items(
1347 Some(bounds.size.width),
1348 bounds.size.height,
1349 &padding,
1350 render_item,
1351 window,
1352 cx,
1353 );
1354
1355 window.take_autoscroll();
1357
1358 if bounds.size.height > padding.top + padding.bottom {
1360 let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
1361 crate::fast::layers::lists::snap_item_origin(
1362 window,
1363 self,
1364 &layout_response.scroll_top,
1365 &mut item_origin,
1366 );
1367 for item in &mut layout_response.item_layouts {
1368 crate::fast::layers::lists::place_list_item(
1369 window,
1370 self,
1371 item.index,
1372 &mut item_origin,
1373 );
1374 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1375 item.element.prepaint_at(item_origin, window, cx);
1376 });
1377
1378 if let Some(autoscroll_bounds) = window.take_autoscroll()
1379 && autoscroll
1380 {
1381 if autoscroll_bounds.top() < bounds.top() {
1382 let mut item_ix = item.index;
1383 let mut offset_in_item = autoscroll_bounds.top() - item_origin.y;
1384
1385 if offset_in_item < Pixels::ZERO {
1390 let mut cursor = self.items.cursor::<Count>(());
1391 cursor.seek(&Count(item_ix), Bias::Right);
1392 while offset_in_item < Pixels::ZERO {
1393 cursor.prev();
1394 let Some(prev_item) = cursor.item() else {
1395 offset_in_item = Pixels::ZERO;
1396 break;
1397 };
1398 let size = prev_item.size().unwrap_or_else(|| {
1399 let mut element = render_item(cursor.start().0, window, cx);
1400 let item_available_size = size(
1401 bounds.size.width.into(),
1402 AvailableSpace::MinContent,
1403 );
1404 crate::fast::layout_key::layout_as_list_item(
1405 &mut element,
1406 cursor.start().0,
1407 item_available_size,
1408 window,
1409 cx,
1410 )
1411 });
1412 item_ix = cursor.start().0;
1413 offset_in_item += size.height;
1414 }
1415 }
1416
1417 return Err(ListOffset {
1418 item_ix,
1419 offset_in_item,
1420 });
1421 } else if autoscroll_bounds.bottom() > bounds.bottom() {
1422 let mut cursor = self.items.cursor::<Count>(());
1423 cursor.seek(&Count(item.index), Bias::Right);
1424 let mut height = bounds.size.height - padding.top - padding.bottom;
1425
1426 height -= autoscroll_bounds.bottom() - item_origin.y;
1428
1429 while height > Pixels::ZERO {
1431 cursor.prev();
1432 let Some(item) = cursor.item() else { break };
1433
1434 let size = item.size().unwrap_or_else(|| {
1435 let mut item = render_item(cursor.start().0, window, cx);
1436 let item_available_size =
1437 size(bounds.size.width.into(), AvailableSpace::MinContent);
1438 crate::fast::layout_key::layout_as_list_item(
1439 &mut item,
1440 cursor.start().0,
1441 item_available_size,
1442 window,
1443 cx,
1444 )
1445 });
1446 height -= size.height;
1447 }
1448
1449 return Err(ListOffset {
1450 item_ix: cursor.start().0,
1451 offset_in_item: if height < Pixels::ZERO {
1452 -height
1453 } else {
1454 Pixels::ZERO
1455 },
1456 });
1457 }
1458 }
1459
1460 item_origin.y += item.size.height;
1461 }
1462 } else {
1463 layout_response.item_layouts.clear();
1464 }
1465
1466 Ok(layout_response)
1467 })
1468 }
1469
1470 fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
1473 let Some(bounds) = self.last_layout_bounds else {
1474 return;
1475 };
1476 let height = bounds.size.height;
1477
1478 let padding = self.last_padding.unwrap_or_default();
1479 let content_height = self
1482 .scrollbar_drag_start_height
1483 .unwrap_or_else(|| self.items.summary().height);
1484 let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
1485 let new_scroll_top = (-point.y).max(px(0.)).min(scroll_max);
1486
1487 let dragged_to_end =
1490 scroll_max > px(0.) && new_scroll_top >= (scroll_max - px(1.0)).max(px(0.));
1491 if dragged_to_end && matches!(self.follow_state, FollowState::Tail { .. }) {
1492 self.follow_state = FollowState::Tail { is_following: true };
1493 let item_count = self.items.summary().count;
1494 self.set_scroll_anchor(Some(ListOffset {
1495 item_ix: item_count,
1496 offset_in_item: px(0.),
1497 }));
1498 return;
1499 }
1500
1501 self.follow_state.stop_following();
1502
1503 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
1504 self.set_scroll_anchor(None);
1505 } else {
1506 let (start, _, _) =
1507 self.items
1508 .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
1509
1510 let scroll_top = ListOffset {
1511 item_ix: start.count,
1512 offset_in_item: new_scroll_top - start.height,
1513 };
1514 self.set_scroll_anchor(Some(scroll_top));
1515 }
1516 }
1517}
1518
1519impl std::fmt::Debug for ListItem {
1520 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1521 match self {
1522 Self::Unmeasured { .. } => write!(f, "Unrendered"),
1523 Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
1524 }
1525 }
1526}
1527
1528#[derive(Debug, Clone, Copy, Default, PartialEq)]
1531pub struct ListOffset {
1532 pub item_ix: usize,
1534 pub offset_in_item: Pixels,
1536}
1537
1538impl Element for List {
1539 type RequestLayoutState = ();
1540 type PrepaintState = ListPrepaintState;
1541
1542 fn id(&self) -> Option<crate::ElementId> {
1543 None
1544 }
1545
1546 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1547 None
1548 }
1549
1550 fn request_layout(
1551 &mut self,
1552 _id: Option<&GlobalElementId>,
1553 _inspector_id: Option<&InspectorElementId>,
1554 window: &mut Window,
1555 cx: &mut App,
1556 ) -> (crate::LayoutId, Self::RequestLayoutState) {
1557 crate::fast::dependencies::note_state_read(cx, &self.state.0.borrow().version);
1558 let layout_id = match self.sizing_behavior {
1559 ListSizingBehavior::Infer => {
1560 let mut style = Style::default();
1561 style.overflow.y = Overflow::Scroll;
1562 style.refine(&self.style);
1563 window.with_text_style(style.text_style().cloned(), |window| {
1564 let state = &mut *self.state.0.borrow_mut();
1565
1566 let available_height = if let Some(last_bounds) = state.last_layout_bounds {
1567 last_bounds.size.height
1568 } else {
1569 state.overdraw
1572 };
1573 let padding = style.padding.to_pixels(
1574 state.last_layout_bounds.unwrap_or_default().size.into(),
1575 window.rem_size(),
1576 );
1577
1578 let layout_response = state.layout_items(
1579 None,
1580 available_height,
1581 &padding,
1582 &mut self.render_item,
1583 window,
1584 cx,
1585 );
1586 let max_element_width = layout_response.max_item_width;
1587
1588 let summary = state.items.summary();
1589 let total_height = summary.height;
1590
1591 window.request_measured_layout(
1592 style,
1593 move |known_dimensions, available_space, _window, _cx| {
1594 let width =
1595 known_dimensions
1596 .width
1597 .unwrap_or(match available_space.width {
1598 AvailableSpace::Definite(x) => x,
1599 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1600 max_element_width
1601 }
1602 });
1603 let height = match available_space.height {
1604 AvailableSpace::Definite(height) => total_height.min(height),
1605 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1606 total_height
1607 }
1608 };
1609 size(width, height)
1610 },
1611 )
1612 })
1613 }
1614 ListSizingBehavior::Auto => {
1615 let mut style = Style::default();
1616 style.refine(&self.style);
1617 window.with_text_style(style.text_style().cloned(), |window| {
1618 window.request_layout(style, None, cx)
1619 })
1620 }
1621 };
1622 (layout_id, ())
1623 }
1624
1625 fn prepaint(
1626 &mut self,
1627 _id: Option<&GlobalElementId>,
1628 _inspector_id: Option<&InspectorElementId>,
1629 bounds: Bounds<Pixels>,
1630 _: &mut Self::RequestLayoutState,
1631 window: &mut Window,
1632 cx: &mut App,
1633 ) -> ListPrepaintState {
1634 let state = &mut *self.state.0.borrow_mut();
1635 state.reset = false;
1636
1637 let mut style = Style::default();
1638 style.refine(&self.style);
1639
1640 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1641
1642 if state
1644 .last_layout_bounds
1645 .is_none_or(|last_bounds| last_bounds.size.width != bounds.size.width)
1646 {
1647 let new_items = SumTree::from_iter(
1648 state.items.iter().map(|item| ListItem::Unmeasured {
1649 size_hint: None,
1650 focus_handle: item.focus_handle(),
1651 }),
1652 (),
1653 );
1654
1655 state.items = new_items;
1656 state.measuring_behavior.reset();
1657 }
1658
1659 let padding = style
1660 .padding
1661 .to_pixels(bounds.size.into(), window.rem_size());
1662 crate::fast::layers::lists::begin_list(window, cx, state, bounds);
1663 let mut autoscroll = true;
1664 let layout = loop {
1665 match state.prepaint_items(
1666 bounds,
1667 padding,
1668 autoscroll,
1669 &mut self.render_item,
1670 window,
1671 cx,
1672 ) {
1673 Ok(layout) => break layout,
1674 Err(autoscroll_request) => {
1675 state.set_scroll_anchor(Some(autoscroll_request));
1676 autoscroll = false;
1677 }
1678 }
1679 };
1680 crate::fast::layers::lists::end_list(window, cx, state, &mut self.render_item, bounds);
1681
1682 state.last_layout_bounds = Some(bounds);
1683 state.last_padding = Some(padding);
1684 ListPrepaintState { hitbox, layout }
1685 }
1686
1687 fn paint(
1688 &mut self,
1689 _id: Option<&GlobalElementId>,
1690 _inspector_id: Option<&InspectorElementId>,
1691 bounds: Bounds<crate::Pixels>,
1692 _: &mut Self::RequestLayoutState,
1693 prepaint: &mut Self::PrepaintState,
1694 window: &mut Window,
1695 cx: &mut App,
1696 ) {
1697 let current_view = window.current_view();
1698
1699 let list_state = self.state.clone();
1705 let height = bounds.size.height;
1706 let scroll_top = prepaint.layout.scroll_top;
1707 let hitbox_id = prepaint.hitbox.id;
1708 let mut accumulated_scroll_delta = ScrollDelta::default();
1709 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
1710 if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
1711 accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
1712 let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1713 list_state.0.borrow_mut().scroll(
1714 &scroll_top,
1715 height,
1716 pixel_delta,
1717 current_view,
1718 window,
1719 cx,
1720 )
1721 }
1722 });
1723
1724 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1725 crate::fast::layers::lists::begin_paint_list(window, cx, &self.state);
1726 for item in &mut prepaint.layout.item_layouts {
1727 crate::fast::layers::lists::paint_row(
1728 window,
1729 cx,
1730 Some(item.index),
1731 |window, cx| item.element.paint(window, cx),
1732 );
1733 }
1734 crate::fast::layers::lists::end_paint_list(window, cx, &self.state);
1735 });
1736 }
1737}
1738
1739impl IntoElement for List {
1740 type Element = Self;
1741
1742 fn into_element(self) -> Self::Element {
1743 self
1744 }
1745}
1746
1747impl Styled for List {
1748 fn style(&mut self) -> &mut StyleRefinement {
1749 &mut self.style
1750 }
1751}
1752
1753impl sum_tree::Item for ListItem {
1754 type Summary = ListItemSummary;
1755
1756 fn summary(&self, _: ()) -> Self::Summary {
1757 match self {
1758 ListItem::Unmeasured {
1759 size_hint,
1760 focus_handle,
1761 } => ListItemSummary {
1762 count: 1,
1763 rendered_count: 0,
1764 unrendered_count: 1,
1765 height: if let Some(size) = size_hint {
1766 size.height
1767 } else {
1768 px(0.)
1769 },
1770 has_focus_handles: focus_handle.is_some(),
1771 has_unknown_height: size_hint.is_none(),
1772 },
1773 ListItem::Measured {
1774 size, focus_handle, ..
1775 } => ListItemSummary {
1776 count: 1,
1777 rendered_count: 1,
1778 unrendered_count: 0,
1779 height: size.height,
1780 has_focus_handles: focus_handle.is_some(),
1781 has_unknown_height: false,
1782 },
1783 }
1784 }
1785}
1786
1787impl sum_tree::ContextLessSummary for ListItemSummary {
1788 fn zero() -> Self {
1789 Default::default()
1790 }
1791
1792 fn add_summary(&mut self, summary: &Self) {
1793 self.count += summary.count;
1794 self.rendered_count += summary.rendered_count;
1795 self.unrendered_count += summary.unrendered_count;
1796 self.height += summary.height;
1797 self.has_focus_handles |= summary.has_focus_handles;
1798 self.has_unknown_height |= summary.has_unknown_height;
1799 }
1800}
1801
1802impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1803 fn zero(_cx: ()) -> Self {
1804 Default::default()
1805 }
1806
1807 fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1808 self.0 += summary.count;
1809 }
1810}
1811
1812impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1813 fn zero(_cx: ()) -> Self {
1814 Default::default()
1815 }
1816
1817 fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1818 self.0 += summary.height;
1819 }
1820}
1821
1822impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1823 fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1824 Ord::cmp(&self.0, &other.count)
1825 }
1826}
1827
1828impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1829 fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1830 Ord::cmp(&self.0, &other.height)
1831 }
1832}
1833
1834#[cfg(test)]
1835mod test {
1836
1837 use gpui::{ScrollDelta, ScrollEvent};
1838 use std::cell::{Cell, RefCell};
1839 use std::rc::Rc;
1840
1841 use crate::{
1842 self as gpui, AnyElement, AppContext, Bounds, Context, Element, FollowMode,
1843 InteractiveElement, IntoElement, ListOffset, ListState, Pixels, Render, Styled,
1844 TestAppContext, VisualTestContext, Window, canvas, div, list, point, px, size,
1845 };
1846
1847 #[gpui::test]
1848 fn test_autoscroll_above_item_top_renders_items_above(cx: &mut TestAppContext) {
1849 let cx = cx.add_empty_window();
1850
1851 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1852 state.scroll_to(gpui::ListOffset {
1853 item_ix: 2,
1854 offset_in_item: px(0.),
1855 });
1856
1857 struct TestView(ListState);
1858 impl Render for TestView {
1859 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1860 list(self.0.clone(), |ix, _, _| {
1861 if ix == 2 {
1862 canvas(
1865 |bounds, window, _| {
1866 window.request_autoscroll(Bounds::from_corners(
1867 point(bounds.left(), bounds.top() - px(30.)),
1868 point(bounds.right(), bounds.top() + px(5.)),
1869 ));
1870 },
1871 |_, _, _, _| {},
1872 )
1873 .h(px(20.))
1874 .w_full()
1875 .into_any()
1876 } else {
1877 div().h(px(20.)).w_full().into_any()
1878 }
1879 })
1880 .w_full()
1881 .h_full()
1882 }
1883 }
1884
1885 cx.draw(point(px(0.), px(0.)), size(px(100.), px(60.)), |_, cx| {
1886 cx.new(|_| TestView(state.clone())).into_any_element()
1887 });
1888
1889 let scroll_top = state.logical_scroll_top();
1891 assert!(
1892 scroll_top.offset_in_item >= px(0.),
1893 "offset_in_item must never be negative (would leave blank space above), got {:?}",
1894 scroll_top.offset_in_item,
1895 );
1896 assert_eq!(scroll_top.item_ix, 0);
1897 assert_eq!(scroll_top.offset_in_item, px(10.));
1898 }
1899
1900 #[gpui::test]
1901 fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
1902 let cx = cx.add_empty_window();
1903
1904 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1905
1906 state.scroll_to(gpui::ListOffset {
1908 item_ix: 0,
1909 offset_in_item: px(0.0),
1910 });
1911
1912 struct TestView(ListState);
1913 impl Render for TestView {
1914 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1915 list(self.0.clone(), |_, _, _| {
1916 div().h(px(10.)).w_full().into_any()
1917 })
1918 .w_full()
1919 .h_full()
1920 }
1921 }
1922
1923 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1925 cx.new(|_| TestView(state.clone())).into_any_element()
1926 });
1927
1928 state.reset(5);
1930
1931 cx.simulate_event(ScrollEvent {
1933 position: point(px(1.), px(1.)),
1934 delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
1935 ..Default::default()
1936 });
1937
1938 assert_eq!(state.logical_scroll_top().item_ix, 0);
1940 assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
1941 }
1942
1943 #[gpui::test]
1944 fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
1945 let cx = cx.add_empty_window();
1946
1947 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1948
1949 struct TestView(ListState);
1950 impl Render for TestView {
1951 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1952 list(self.0.clone(), |_, _, _| {
1953 div().h(px(20.)).w_full().into_any()
1954 })
1955 .w_full()
1956 .h_full()
1957 }
1958 }
1959
1960 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1962 cx.new(|_| TestView(state.clone())).into_any_element()
1963 });
1964
1965 state.scroll_by(px(30.));
1967
1968 let offset = state.logical_scroll_top();
1970 assert_eq!(offset.item_ix, 1);
1971 assert_eq!(offset.offset_in_item, px(10.));
1972
1973 state.scroll_by(px(-30.));
1975
1976 let offset = state.logical_scroll_top();
1978 assert_eq!(offset.item_ix, 0);
1979 assert_eq!(offset.offset_in_item, px(0.));
1980
1981 state.scroll_by(px(0.));
1983 let offset = state.logical_scroll_top();
1984 assert_eq!(offset.item_ix, 0);
1985 assert_eq!(offset.offset_in_item, px(0.));
1986 }
1987
1988 #[gpui::test]
1989 fn test_child_scroll_handler_can_stop_list_scroll(cx: &mut TestAppContext) {
1990 let cx = cx.add_empty_window();
1991
1992 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1993 let child_saw_event = Rc::new(Cell::new(false));
1994
1995 struct TestView {
1996 state: ListState,
1997 child_saw_event: Rc<Cell<bool>>,
1998 }
1999 impl Render for TestView {
2000 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2001 let child_saw_event = self.child_saw_event.clone();
2002 list(self.state.clone(), move |_, _, _| {
2003 let child_saw_event = child_saw_event.clone();
2004 div()
2005 .h(px(20.))
2006 .w_full()
2007 .on_scroll(move |_, _, cx| {
2008 child_saw_event.set(true);
2009 cx.stop_propagation();
2010 })
2011 .into_any()
2012 })
2013 .w_full()
2014 .h_full()
2015 }
2016 }
2017
2018 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
2019 cx.new(|_| TestView {
2020 state: state.clone(),
2021 child_saw_event: child_saw_event.clone(),
2022 })
2023 .into_any_element()
2024 });
2025
2026 cx.simulate_event(ScrollEvent {
2027 position: point(px(50.), px(10.)),
2028 delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2029 ..Default::default()
2030 });
2031
2032 assert!(
2033 child_saw_event.get(),
2034 "the child's scroll-wheel handler should run"
2035 );
2036 let offset = state.logical_scroll_top();
2038 assert_eq!(offset.item_ix, 0);
2039 assert_eq!(offset.offset_in_item, px(0.));
2040 }
2041
2042 #[gpui::test]
2043 fn test_item_viewport_queries_return_none_before_layout(_cx: &mut TestAppContext) {
2044 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2045
2046 assert_eq!(state.item_is_above_viewport(0), None);
2047 assert_eq!(state.item_is_below_viewport(0), None);
2048 }
2049
2050 #[gpui::test]
2051 fn test_item_viewport_queries_before_logical_scroll_top(cx: &mut TestAppContext) {
2052 let cx = cx.add_empty_window();
2053
2054 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2055
2056 state.scroll_to(gpui::ListOffset {
2057 item_ix: 2,
2058 offset_in_item: px(0.),
2059 });
2060 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2061 cx.new(|_| TestListView(state.clone())).into_any_element()
2062 });
2063
2064 assert_eq!(state.item_is_above_viewport(1), Some(true));
2065 assert_eq!(state.item_is_below_viewport(1), Some(false));
2066 }
2067
2068 #[gpui::test]
2069 fn test_item_viewport_queries_measured_item_inside_viewport(cx: &mut TestAppContext) {
2070 let cx = cx.add_empty_window();
2071
2072 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2073
2074 state.scroll_to(gpui::ListOffset {
2075 item_ix: 2,
2076 offset_in_item: px(0.),
2077 });
2078 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2079 cx.new(|_| TestListView(state.clone())).into_any_element()
2080 });
2081
2082 assert_eq!(state.item_is_above_viewport(2), Some(false));
2083 assert_eq!(state.item_is_below_viewport(2), Some(false));
2084 }
2085
2086 #[gpui::test]
2087 fn test_item_viewport_queries_measured_item_above_viewport(cx: &mut TestAppContext) {
2088 let cx = cx.add_empty_window();
2089
2090 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2091
2092 state.scroll_to(gpui::ListOffset {
2093 item_ix: 2,
2094 offset_in_item: px(20.),
2095 });
2096 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2097 cx.new(|_| TestListView(state.clone())).into_any_element()
2098 });
2099
2100 assert_eq!(state.item_is_above_viewport(2), Some(true));
2101 assert_eq!(state.item_is_below_viewport(2), Some(false));
2102 }
2103
2104 #[gpui::test]
2105 fn test_item_viewport_queries_measured_item_below_viewport(cx: &mut TestAppContext) {
2106 let cx = cx.add_empty_window();
2107
2108 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2109
2110 state.scroll_to(gpui::ListOffset {
2111 item_ix: 2,
2112 offset_in_item: px(0.),
2113 });
2114 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2115 cx.new(|_| TestListView(state.clone())).into_any_element()
2116 });
2117
2118 assert_eq!(state.item_is_above_viewport(3), Some(false));
2119 assert_eq!(state.item_is_below_viewport(3), Some(true));
2120 }
2121
2122 #[gpui::test]
2123 fn test_item_viewport_queries_remain_stable_with_zero_height_viewport(cx: &mut TestAppContext) {
2124 let cx = cx.add_empty_window();
2125
2126 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2127
2128 state.scroll_to(gpui::ListOffset {
2129 item_ix: 2,
2130 offset_in_item: px(0.),
2131 });
2132 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2133 cx.new(|_| TestListView(state.clone())).into_any_element()
2134 });
2135
2136 assert_eq!(state.item_is_above_viewport(3), Some(false));
2137 assert_eq!(state.item_is_below_viewport(3), Some(true));
2138
2139 cx.draw(point(px(0.), px(0.)), size(px(100.), px(0.)), |_, cx| {
2144 cx.new(|_| TestListView(state.clone())).into_any_element()
2145 });
2146
2147 assert_eq!(state.item_is_above_viewport(1), Some(true));
2148 assert_eq!(state.item_is_below_viewport(1), Some(false));
2149 assert_eq!(state.item_is_above_viewport(3), Some(false));
2150 assert_eq!(state.item_is_below_viewport(3), Some(true));
2151 }
2152
2153 #[gpui::test]
2154 fn test_item_viewport_queries_after_scroll_to_end_before_layout(cx: &mut TestAppContext) {
2155 let cx = cx.add_empty_window();
2156
2157 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2158
2159 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2160 cx.new(|_| TestListView(state.clone())).into_any_element()
2161 });
2162
2163 state.scroll_to_end();
2164
2165 assert_eq!(state.logical_scroll_top().item_ix, state.item_count());
2166 assert_eq!(state.item_is_above_viewport(0), Some(true));
2167 assert_eq!(state.item_is_below_viewport(0), Some(false));
2168 }
2169
2170 #[gpui::test]
2171 fn test_measure_all_after_width_change(cx: &mut TestAppContext) {
2172 let cx = cx.add_empty_window();
2173
2174 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2175
2176 struct TestView(ListState);
2177 impl Render for TestView {
2178 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2179 list(self.0.clone(), |_, _, _| {
2180 div().h(px(50.)).w_full().into_any()
2181 })
2182 .w_full()
2183 .h_full()
2184 }
2185 }
2186
2187 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2188
2189 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2192 view.clone().into_any_element()
2193 });
2194 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2195
2196 cx.draw(point(px(0.), px(0.)), size(px(200.), px(200.)), |_, _| {
2200 view.into_any_element()
2201 });
2202 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2203 }
2204
2205 #[gpui::test]
2206 fn test_remeasure(cx: &mut TestAppContext) {
2207 let cx = cx.add_empty_window();
2208
2209 let item_height = Rc::new(Cell::new(100usize));
2213 let state = ListState::new(10, crate::ListAlignment::Top, px(10.));
2214
2215 struct TestView {
2216 state: ListState,
2217 item_height: Rc<Cell<usize>>,
2218 }
2219
2220 impl Render for TestView {
2221 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2222 let height = self.item_height.get();
2223 list(self.state.clone(), move |_, _, _| {
2224 div().h(px(height as f32)).w_full().into_any()
2225 })
2226 .w_full()
2227 .h_full()
2228 }
2229 }
2230
2231 let state_clone = state.clone();
2232 let item_height_clone = item_height.clone();
2233 let view = cx.update(|_, cx| {
2234 cx.new(|_| TestView {
2235 state: state_clone,
2236 item_height: item_height_clone,
2237 })
2238 });
2239
2240 state.scroll_to(gpui::ListOffset {
2243 item_ix: 2,
2244 offset_in_item: px(40.),
2245 });
2246
2247 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2248 view.clone().into_any_element()
2249 });
2250
2251 let offset = state.logical_scroll_top();
2252 assert_eq!(offset.item_ix, 2);
2253 assert_eq!(offset.offset_in_item, px(40.));
2254
2255 item_height.set(50);
2260 state.remeasure();
2261
2262 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2263 view.into_any_element()
2264 });
2265
2266 let offset = state.logical_scroll_top();
2267 assert_eq!(offset.item_ix, 2);
2268 assert_eq!(offset.offset_in_item, px(20.));
2269 }
2270
2271 #[gpui::test]
2272 fn test_remeasure_item_preserves_scroll_offset(cx: &mut TestAppContext) {
2273 let cx = cx.add_empty_window();
2274
2275 let item_height = Rc::new(Cell::new(100usize));
2276 let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2277
2278 struct TestView {
2279 state: ListState,
2280 item_height: Rc<Cell<usize>>,
2281 }
2282
2283 impl Render for TestView {
2284 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2285 let height = self.item_height.get();
2286 list(self.state.clone(), move |index, _, _| {
2287 let height = if index == 5 { height } else { 100 };
2288 div().h(px(height as f32)).w_full().into_any()
2289 })
2290 .w_full()
2291 .h_full()
2292 }
2293 }
2294
2295 let state_clone = state.clone();
2296 let item_height_clone = item_height.clone();
2297 let view = cx.update(|_, cx| {
2298 cx.new(|_| TestView {
2299 state: state_clone,
2300 item_height: item_height_clone,
2301 })
2302 });
2303
2304 state.scroll_to(gpui::ListOffset {
2305 item_ix: 5,
2306 offset_in_item: px(40.),
2307 });
2308
2309 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2310 view.clone().into_any_element()
2311 });
2312
2313 item_height.set(200);
2314 state.remeasure_items(5..6);
2315
2316 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2317 view.into_any_element()
2318 });
2319
2320 let offset = state.logical_scroll_top();
2321 assert_eq!(offset.item_ix, 5);
2322 assert_eq!(offset.offset_in_item, px(40.));
2323 }
2324
2325 #[gpui::test]
2326 fn test_provisional_item_heights_keep_scroll_anchor(cx: &mut TestAppContext) {
2327 let cx = cx.add_empty_window();
2328 let state = ListState::new(20, crate::ListAlignment::Top, px(100.));
2329 let painted = Rc::new(RefCell::new(Vec::new()));
2330 let first_rendered = Rc::new(Cell::new(None::<usize>));
2331 let ready = item_readiness(&state, false);
2332 state.set_follow_mode(FollowMode::Tail);
2333 state.scroll_to(list_offset(10, 40.));
2334
2335 for (height, measurement_ready) in [(0., false), (100., false), (100., true)] {
2336 ready.set(measurement_ready);
2337 painted.borrow_mut().clear();
2338 first_rendered.set(None);
2339 draw_list(
2340 &state,
2341 200.,
2342 {
2343 let painted = painted.clone();
2344 let first_rendered = first_rendered.clone();
2345 move |index| {
2346 first_rendered.set(Some(first_rendered.get().unwrap_or(index).min(index)));
2347 painted_item(index, height, &painted)
2348 }
2349 },
2350 cx,
2351 );
2352 assert_eq!(state.logical_scroll_top(), list_offset(10, 40.));
2353 assert!(!state.is_following_tail());
2354 assert_eq!(
2355 first_rendered.get(),
2356 Some(if measurement_ready { 9 } else { 10 })
2357 );
2358 if height > 0. {
2359 assert_eq!(
2360 painted.borrow().as_slice(),
2361 &[
2362 (10, px(-40.), px(60.)),
2363 (11, px(60.), px(160.)),
2364 (12, px(160.), px(260.)),
2365 ]
2366 );
2367 }
2368 }
2369 }
2370
2371 #[gpui::test]
2372 fn test_unready_measurements_preserve_pending_fraction(cx: &mut TestAppContext) {
2373 let cx = cx.add_empty_window();
2374 for (provisional_height, destination, final_height, expected_offset) in [
2375 (Some(200.), None, 200., 100.),
2376 (None, Some(40.), 200., 80.),
2377 (Some(200.), Some(50.), 200., 50.),
2378 (Some(0.), Some(40.), 20., 20.),
2379 (Some(10.), Some(40.), 100., 40.),
2380 (Some(200.), Some(50.), 300., 50.),
2381 ] {
2382 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2383 let painted = Rc::new(RefCell::new(Vec::new()));
2384 let draw = |height, cx: &mut VisualTestContext| {
2385 painted.borrow_mut().clear();
2386 let painted = painted.clone();
2387 draw_list(
2388 &state,
2389 200.,
2390 move |index| {
2391 painted_item(index, if index == 5 { height } else { 100. }, &painted)
2392 },
2393 cx,
2394 );
2395 };
2396 let ready = item_readiness(&state, true);
2397 state.scroll_to(list_offset(5, 50.));
2398 draw(100., cx);
2399 ready.set(false);
2400 state.remeasure();
2401 if let Some(height) = provisional_height {
2402 for height in [0., height, height] {
2403 draw(height, cx);
2404 assert_eq!(state.logical_scroll_top(), list_offset(5, 50.));
2405 }
2406 }
2407 if let Some(offset) = destination {
2408 state.scroll_to(list_offset(5, offset));
2409 }
2410 ready.set(true);
2411 for _ in 0..2 {
2412 draw(final_height, cx);
2413 assert_eq!(state.logical_scroll_top(), list_offset(5, expected_offset));
2414 assert_eq!(
2415 painted.borrow().first().copied(),
2416 Some((5, px(-expected_offset), px(final_height - expected_offset)))
2417 );
2418 }
2419 }
2420 }
2421
2422 #[gpui::test]
2423 fn test_navigation_cancels_provisional_and_paints_destination(cx: &mut TestAppContext) {
2424 let cx = cx.add_empty_window();
2425 for measured in [false, true] {
2426 let navigations: [(&str, fn(&ListState), usize, f32); 7] = [
2427 (
2428 "scroll_to",
2429 |state| state.scroll_to(list_offset(12, 0.)),
2430 12,
2431 0.,
2432 ),
2433 ("end", ListState::scroll_to_end, 19, 150.),
2434 ("down", |state| state.scroll_by(px(5000.)), 19, 150.),
2435 (
2436 "up",
2437 |state| state.scroll_by(px(-5000.)),
2438 if measured { 0 } else { 6 },
2439 0.,
2440 ),
2441 (
2442 "reveal_below",
2443 |state| state.scroll_to_reveal_item(10),
2444 10,
2445 150.,
2446 ),
2447 (
2448 "reveal_above",
2449 |state| state.scroll_to_reveal_item(0),
2450 0,
2451 0.,
2452 ),
2453 (
2454 "follow_tail",
2455 |state| state.set_follow_mode(FollowMode::Tail),
2456 19,
2457 150.,
2458 ),
2459 ];
2460 for (name, navigate, destination, top) in navigations {
2461 let state = ListState::new(20, crate::ListAlignment::Top, px(0.));
2462 let state = if measured { state.measure_all() } else { state };
2463 let painted = Rc::new(RefCell::new(Vec::new()));
2464 let draw = |cx: &mut VisualTestContext| {
2465 painted.borrow_mut().clear();
2466 let painted = painted.clone();
2467 draw_list(
2468 &state,
2469 200.,
2470 move |index| {
2471 painted_item(index, if index == 5 { 0. } else { 50. }, &painted)
2472 },
2473 cx,
2474 );
2475 };
2476 state.set_item_measurement_readiness(|index, _| index != 5);
2477 state.scroll_to(list_offset(5, 20.));
2478 state.remeasure_items(5..6);
2479 draw(cx);
2480 assert!(state.0.borrow().is_provisional(), "{name}");
2481 navigate(&state);
2482 assert!(!state.0.borrow().is_provisional(), "{name}");
2483 draw(cx);
2484 assert!(!state.0.borrow().is_provisional(), "{name}");
2485 assert_eq!(
2486 painted
2487 .borrow()
2488 .iter()
2489 .find(|(index, _, _)| *index == destination)
2490 .copied(),
2491 Some((destination, px(top), px(top + 50.))),
2492 "{name}, measured={measured}",
2493 );
2494 }
2495 }
2496
2497 let navigations: [(&str, fn(&ListState)); 6] = [
2498 ("end_sentinel", |state| state.scroll_to(list_offset(3, 0.))),
2499 ("scroll_to_end", ListState::scroll_to_end),
2500 ("follow_tail", |state| {
2501 state.set_follow_mode(FollowMode::Tail)
2502 }),
2503 ("horizontal", ListState::scroll_to_end),
2504 ("pause_tail", |state| {
2505 state.set_follow_mode(FollowMode::Tail)
2506 }),
2507 ("disable_tail", |state| {
2508 state.set_follow_mode(FollowMode::Tail)
2509 }),
2510 ];
2511 for (name, navigate) in navigations {
2512 let state = ListState::new(3, crate::ListAlignment::Top, px(0.)).measure_all();
2513 let ready = item_readiness(&state, false);
2514 let painted = Rc::new(RefCell::new(Vec::new()));
2515 let draw = |height, cx: &mut VisualTestContext| {
2516 painted.borrow_mut().clear();
2517 let painted = painted.clone();
2518 draw_list(
2519 &state,
2520 200.,
2521 move |index| painted_item(index, height, &painted),
2522 cx,
2523 );
2524 };
2525 navigate(&state);
2526 for (height, measurement_ready, expected) in [
2527 (
2528 100.,
2529 false,
2530 [(1, px(0.), px(100.)), (2, px(100.), px(200.))],
2531 ),
2532 (
2533 150.,
2534 true,
2535 [(1, px(-100.), px(50.)), (2, px(50.), px(200.))],
2536 ),
2537 ] {
2538 if measurement_ready {
2539 match name {
2540 "horizontal" => cx.simulate_event(ScrollEvent {
2541 position: point(px(50.), px(100.)),
2542 delta: ScrollDelta::Pixels(point(px(20.), px(0.))),
2543 ..ScrollEvent::default()
2544 }),
2545 "pause_tail" => state.pause_following_tail(),
2546 "disable_tail" => state.set_follow_mode(FollowMode::Normal),
2547 _ => {}
2548 }
2549 }
2550 ready.set(measurement_ready);
2551 draw(height, cx);
2552 if !measurement_ready {
2553 assert_eq!(
2554 state.scroll_px_offset_for_scrollbar().y,
2555 px(-100.),
2556 "{name}"
2557 );
2558 assert_eq!(state.logical_scroll_top(), list_offset(1, 0.), "{name}");
2559 assert_eq!(state.item_is_above_viewport(2), None, "{name}");
2560 }
2561 let paused = name == "pause_tail" || name == "disable_tail";
2562 let expected = if measurement_ready && paused {
2563 [(1, px(0.), px(150.)), (2, px(150.), px(300.))]
2564 } else {
2565 expected
2566 };
2567 assert_eq!(
2568 state.is_following_tail(),
2569 name == "follow_tail" || (paused && !measurement_ready),
2570 "{name}"
2571 );
2572 assert_eq!(painted.borrow().as_slice(), &expected, "{name}");
2573 }
2574 ready.set(false);
2575 navigate(&state);
2576 draw(150., cx);
2577 state.scroll_by(px(-20.));
2578 draw(150., cx);
2579 assert_eq!(state.logical_scroll_top(), list_offset(1, 80.), "{name}");
2580 assert!(!state.is_following_tail(), "{name}");
2581 assert_eq!(
2582 painted.borrow().as_slice(),
2583 &[(1, px(-80.), px(70.)), (2, px(70.), px(220.)),],
2584 "{name}"
2585 );
2586 }
2587 }
2588
2589 #[gpui::test]
2590 fn test_unready_overdraw_and_backfill_preserve_scroll_anchor(cx: &mut TestAppContext) {
2591 let cx = cx.add_empty_window();
2592 for (overdraw, anchor, unready_item) in
2593 [(100., list_offset(0, 0.), 2), (0., list_offset(2, 40.), 1)]
2594 {
2595 let state = ListState::new(3, crate::ListAlignment::Top, px(overdraw));
2596 let ready = Rc::new(Cell::new(false));
2597 state.set_item_measurement_readiness({
2598 let ready = ready.clone();
2599 move |index, _| index != unready_item || ready.get()
2600 });
2601 let painted = Rc::new(RefCell::new(Vec::new()));
2602 let draw = |height, cx: &mut VisualTestContext| {
2603 painted.borrow_mut().clear();
2604 let painted = painted.clone();
2605 draw_list(
2606 &state,
2607 200.,
2608 move |index| {
2609 let height = if index == unready_item { height } else { 100. };
2610 painted_item(index, height, &painted)
2611 },
2612 cx,
2613 );
2614 };
2615 state.set_follow_mode(FollowMode::Tail);
2616 state.scroll_to(anchor);
2617 draw(0., cx);
2618 assert_eq!(state.logical_scroll_top(), anchor);
2619 assert!(!state.is_following_tail());
2620 assert_eq!(
2621 *painted.borrow(),
2622 if unready_item == 2 {
2623 vec![(0, px(0.), px(100.)), (1, px(100.), px(200.))]
2624 } else {
2625 vec![(2, px(-40.), px(60.))]
2626 }
2627 );
2628 ready.set(true);
2629 draw(500., cx);
2630 if unready_item == 2 {
2631 assert_eq!(state.logical_scroll_top(), anchor);
2632 assert!(!state.is_following_tail());
2633 assert_eq!(state.max_offset_for_scrollbar().y, px(500.));
2634 assert_eq!(
2635 painted.borrow().as_slice(),
2636 &[(0, px(0.), px(100.)), (1, px(100.), px(200.))]
2637 );
2638 } else {
2639 assert_eq!(state.logical_scroll_top(), list_offset(1, 400.));
2640 assert!(state.is_following_tail());
2641 assert_eq!(
2642 painted.borrow().as_slice(),
2643 &[(1, px(-400.), px(100.)), (2, px(100.), px(200.))]
2644 );
2645 }
2646 }
2647 }
2648
2649 #[gpui::test]
2650 fn test_unready_overdraw_stops_at_first_pending_item(cx: &mut TestAppContext) {
2651 let cx = cx.add_empty_window();
2652 for anchor in [0, 10] {
2653 let state = ListState::new(13, crate::ListAlignment::Top, px(100.));
2654 let ready = Rc::new(Cell::new(false));
2655 let initially_ready = move |index| {
2656 if anchor == 0 { index < 2 } else { index >= 10 }
2657 };
2658 state.set_item_measurement_readiness({
2659 let ready = ready.clone();
2660 move |index, _| initially_ready(index) || ready.get()
2661 });
2662 state.scroll_to(list_offset(anchor, 0.));
2663 let rendered = Rc::new(RefCell::new(Vec::new()));
2664 let painted = Rc::new(RefCell::new(Vec::new()));
2665 let expected_frames = if anchor == 0 {
2666 [vec![0, 1, 2], vec![0, 1, 2], vec![0, 1, 2], vec![0, 1]]
2667 } else {
2668 [
2669 vec![10, 11, 12, 9],
2670 vec![10, 11, 9],
2671 vec![10, 11, 9],
2672 vec![10, 11],
2673 ]
2674 };
2675 for (frame, expected_rendered) in expected_frames.into_iter().enumerate() {
2676 let measurement_ready = frame >= 2;
2677 ready.set(measurement_ready);
2678 rendered.borrow_mut().clear();
2679 painted.borrow_mut().clear();
2680 draw_list(
2681 &state,
2682 200.,
2683 {
2684 let rendered = rendered.clone();
2685 let painted = painted.clone();
2686 move |index| {
2687 rendered.borrow_mut().push(index);
2688 let height = if initially_ready(index) || measurement_ready {
2689 100.
2690 } else {
2691 0.
2692 };
2693 painted_item(index, height, &painted)
2694 }
2695 },
2696 cx,
2697 );
2698 assert_eq!(*rendered.borrow(), expected_rendered);
2699 assert_eq!(state.item_count(), 13);
2700 assert_eq!(state.logical_scroll_top(), list_offset(anchor, 0.));
2701 assert_eq!(
2702 painted.borrow().as_slice(),
2703 &[(anchor, px(0.), px(100.)), (anchor + 1, px(100.), px(200.))]
2704 );
2705 }
2706 }
2707 }
2708
2709 #[gpui::test]
2710 fn test_scrollbar_and_reset_do_not_resurrect_provisional(cx: &mut TestAppContext) {
2711 let cx = cx.add_empty_window();
2712 let state = ListState::new(20, crate::ListAlignment::Top, px(0.));
2713 let painted = Rc::new(RefCell::new(Vec::new()));
2714 let draw = |cx: &mut VisualTestContext| {
2715 painted.borrow_mut().clear();
2716 let painted = painted.clone();
2717 draw_list(
2718 &state,
2719 200.,
2720 move |index| painted_item(index, if index == 5 { 0. } else { 50. }, &painted),
2721 cx,
2722 );
2723 };
2724 state.set_item_measurement_readiness(|index, _| index != 5);
2725 assert!(!state.0.borrow().is_provisional());
2726 state.set_follow_mode(FollowMode::Tail);
2727 for intervening_frame in [false, true] {
2728 state.scroll_to(list_offset(5, 20.));
2729 state.remeasure_items(5..6);
2730 draw(cx);
2731 state.scrollbar_drag_started();
2732 if intervening_frame {
2733 draw(cx);
2734 assert!(state.0.borrow().is_provisional());
2735 }
2736 state.set_offset_from_scrollbar(point(px(0.), px(-10_000.)));
2737 assert!(!state.0.borrow().is_provisional());
2738 state.scrollbar_drag_ended();
2739 assert!(!state.is_scrollbar_dragging());
2740 draw(cx);
2741 assert_eq!(
2742 painted.borrow().last().copied(),
2743 Some((19, px(150.), px(200.)))
2744 );
2745 assert!(!state.0.borrow().is_provisional());
2746 state.scroll_to(list_offset(5, 20.));
2747 assert!(!state.0.borrow().is_provisional());
2748 draw(cx);
2749 assert!(state.0.borrow().is_provisional());
2750 assert_eq!(state.logical_scroll_top(), list_offset(5, 20.));
2751 }
2752 state.remeasure_items(5..6);
2753 state.reset(20);
2754 assert!(!state.0.borrow().is_provisional());
2755 draw(cx);
2756 assert!(!state.0.borrow().is_provisional());
2757 assert_eq!(state.logical_scroll_top(), ListOffset::default());
2758 assert_eq!(
2759 painted.borrow().first().copied(),
2760 Some((0, px(0.), px(50.)))
2761 );
2762 }
2763
2764 #[gpui::test]
2765 fn test_splice_preserves_only_surviving_scroll_offsets(cx: &mut TestAppContext) {
2766 let cx = cx.add_empty_window();
2767 let painted = Rc::new(RefCell::new(Vec::new()));
2768 let draw = |state: &ListState, height, cx: &mut VisualTestContext| {
2769 painted.borrow_mut().clear();
2770 let painted = painted.clone();
2771 draw_list(
2772 state,
2773 200.,
2774 move |index| painted_item(index, height, &painted),
2775 cx,
2776 );
2777 };
2778 for (provisional, replacement_count) in [(true, 0), (false, 1)] {
2779 let state = ListState::new(20, crate::ListAlignment::Top, px(0.));
2780 let ready = item_readiness(&state, !provisional);
2781 state.scroll_to(list_offset(8, 50.));
2782 state.remeasure_items(8..9);
2783 if provisional {
2784 draw(&state, 100., cx);
2785 }
2786 state.splice(8..9, replacement_count);
2787 assert!(!state.0.borrow().is_provisional());
2788 ready.set(true);
2789 draw(&state, 100., cx);
2790 assert_eq!(state.logical_scroll_top(), list_offset(8, 0.));
2791 assert_eq!(
2792 painted.borrow().first().copied(),
2793 Some((8, px(0.), px(100.)))
2794 );
2795 }
2796 let state = ListState::new(20, crate::ListAlignment::Top, px(0.)).measure_all();
2797 state.scroll_to(list_offset(8, 50.));
2798 draw(&state, 100., cx);
2799 state.remeasure();
2800 state.splice(0..2, 0);
2801 draw(&state, 80., cx);
2802 assert_eq!(state.logical_scroll_top(), list_offset(6, 40.));
2803 assert_eq!(
2804 painted.borrow().first().copied(),
2805 Some((6, px(-40.), px(40.)))
2806 );
2807 let ready = item_readiness(&state, false);
2808 state.remeasure_items(6..7);
2809 state.splice(8..10, 3);
2810 draw(&state, 100., cx);
2811 assert!(state.0.borrow().is_provisional());
2812 assert_eq!(state.logical_scroll_top(), list_offset(6, 40.));
2813 state.splice(0..0, 2);
2814 assert!(!state.0.borrow().is_provisional());
2815 draw(&state, 100., cx);
2816 assert!(state.0.borrow().is_provisional());
2817 assert_eq!(state.logical_scroll_top(), list_offset(8, 40.));
2818 ready.set(true);
2819 draw(&state, 100., cx);
2820 assert_eq!(state.logical_scroll_top(), list_offset(8, 40.));
2821 assert_eq!(
2822 painted.borrow().first().copied(),
2823 Some((8, px(-40.), px(60.)))
2824 );
2825 }
2826
2827 #[gpui::test]
2828 fn test_child_autoscroll_overrides_pending_and_release_fills_viewport(cx: &mut TestAppContext) {
2829 let cx = cx.add_empty_window();
2830 for (count, child, request, expected, released) in [
2831 (10, 2, 40.0..45.0, list_offset(2, 40.), list_offset(2, 40.)),
2832 (3, 2, 40.0..45.0, list_offset(2, 40.), list_offset(1, 0.)),
2833 (10, 4, 80.0..90.0, list_offset(2, 90.), list_offset(2, 90.)),
2834 (10, 2, -130.0..5.0, list_offset(0, 70.), list_offset(0, 70.)),
2835 (10, 2, -250.0..5.0, list_offset(0, 0.), list_offset(0, 0.)),
2836 ] {
2837 let state = ListState::new(count, crate::ListAlignment::Top, px(0.));
2838 let requested = Rc::new(Cell::new(false));
2839 let painted = Rc::new(RefCell::new(Vec::new()));
2840 let draw = |cx: &mut VisualTestContext| {
2841 painted.borrow_mut().clear();
2842 let painted = painted.clone();
2843 let requested = requested.clone();
2844 let request = request.clone();
2845 draw_list(
2846 &state,
2847 200.,
2848 move |index| {
2849 let painted = painted.clone();
2850 let requested = requested.clone();
2851 let request = request.clone();
2852 canvas(
2853 move |bounds, window, _| {
2854 if index == child && !requested.replace(true) {
2855 window.request_autoscroll(Bounds::from_corners(
2856 point(bounds.left(), bounds.top() + px(request.start)),
2857 point(bounds.right(), bounds.top() + px(request.end)),
2858 ));
2859 }
2860 },
2861 move |bounds, _, _, _| {
2862 painted
2863 .borrow_mut()
2864 .push((index, bounds.top(), bounds.bottom()));
2865 },
2866 )
2867 .h(px(100.))
2868 .w_full()
2869 .into_any()
2870 },
2871 cx,
2872 );
2873 };
2874 let ready = item_readiness(&state, false);
2875 state.scroll_to(list_offset(2, 50.));
2876 state.remeasure_items(2..3);
2877 for _ in 0..2 {
2878 draw(cx);
2879 assert!(requested.get());
2880 assert!(state.0.borrow().is_provisional());
2881 assert_eq!(state.logical_scroll_top(), expected);
2882 assert_eq!(
2883 painted.borrow().first().copied(),
2884 Some((
2885 expected.item_ix,
2886 -expected.offset_in_item,
2887 px(100.) - expected.offset_in_item,
2888 ))
2889 );
2890 }
2891 ready.set(true);
2892 draw(cx);
2893 assert!(!state.0.borrow().is_provisional());
2894 assert_eq!(state.logical_scroll_top(), released);
2895 let visible_count = if released.offset_in_item == px(0.) {
2896 2
2897 } else {
2898 3
2899 };
2900 assert_eq!(
2901 painted.borrow().as_slice(),
2902 (0..visible_count)
2903 .map(|index| {
2904 let top = px(index as f32 * 100.) - released.offset_in_item;
2905 (released.item_ix + index, top, top + px(100.))
2906 })
2907 .collect::<Vec<_>>()
2908 .as_slice()
2909 );
2910 }
2911 }
2912
2913 #[gpui::test]
2914 fn test_remeasure_then_scroll_does_not_revert_scroll_position(cx: &mut TestAppContext) {
2915 let cx = cx.add_empty_window();
2916
2917 let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2918
2919 struct TestView(ListState);
2920 impl Render for TestView {
2921 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2922 list(self.0.clone(), |_, _, _| {
2923 div().h(px(100.)).w_full().into_any()
2924 })
2925 .w_full()
2926 .h_full()
2927 }
2928 }
2929
2930 let view = {
2931 let state = state.clone();
2932 cx.update(|_, cx| cx.new(|_| TestView(state)))
2933 };
2934
2935 state.scroll_to(gpui::ListOffset {
2936 item_ix: 5,
2937 offset_in_item: px(40.),
2938 });
2939
2940 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2941 view.clone().into_any_element()
2942 });
2943
2944 state.remeasure_items(5..6);
2945
2946 cx.simulate_event(ScrollEvent {
2947 position: point(px(50.), px(100.)),
2948 delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2949 ..Default::default()
2950 });
2951
2952 let offset = state.logical_scroll_top();
2953 assert_eq!(offset.item_ix, 5);
2954 assert_eq!(offset.offset_in_item, px(70.));
2955
2956 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2957 view.into_any_element()
2958 });
2959
2960 let offset = state.logical_scroll_top();
2961 assert_eq!(offset.item_ix, 5);
2962 assert_eq!(
2963 offset.offset_in_item,
2964 px(70.),
2965 "scrolling after a remeasure should not be reverted by the stale pending scroll"
2966 );
2967 }
2968
2969 #[gpui::test]
2970 fn test_scroll_after_remeasure_clamps_to_shrunk_item_height(cx: &mut TestAppContext) {
2971 let cx = cx.add_empty_window();
2972 for provisional in [false, true] {
2973 let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2974 let painted = Rc::new(RefCell::new(Vec::new()));
2975 let draw = |height, cx: &mut VisualTestContext| {
2976 painted.borrow_mut().clear();
2977 let painted = painted.clone();
2978 draw_list(
2979 &state,
2980 200.,
2981 move |index| {
2982 painted_item(index, if index == 5 { height } else { 100. }, &painted)
2983 },
2984 cx,
2985 );
2986 };
2987 let ready = item_readiness(&state, true);
2988 state.scroll_to(list_offset(5, 40.));
2989 draw(100., cx);
2990 ready.set(!provisional);
2991 state.remeasure_items(5..6);
2992 if provisional {
2993 draw(100., cx);
2994 }
2995 ready.set(true);
2996 cx.simulate_event(ScrollEvent {
2997 position: point(px(50.), px(100.)),
2998 delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2999 ..ScrollEvent::default()
3000 });
3001 assert_eq!(state.logical_scroll_top(), list_offset(5, 70.));
3002 for _ in 0..2 {
3003 draw(50., cx);
3004 assert_eq!(state.logical_scroll_top(), list_offset(5, 50.));
3005 assert_eq!(
3006 painted
3007 .borrow()
3008 .iter()
3009 .find(|(index, _, _)| *index == 6)
3010 .copied(),
3011 Some((6, px(0.), px(100.)))
3012 );
3013 }
3014 }
3015 }
3016
3017 #[gpui::test]
3018 fn test_follow_tail_stays_at_bottom_as_items_grow(cx: &mut TestAppContext) {
3019 let cx = cx.add_empty_window();
3020
3021 let item_height = Rc::new(Cell::new(50usize));
3024 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3025
3026 struct TestView {
3027 state: ListState,
3028 item_height: Rc<Cell<usize>>,
3029 }
3030 impl Render for TestView {
3031 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3032 let height = self.item_height.get();
3033 list(self.state.clone(), move |_, _, _| {
3034 div().h(px(height as f32)).w_full().into_any()
3035 })
3036 .w_full()
3037 .h_full()
3038 }
3039 }
3040
3041 let state_clone = state.clone();
3042 let item_height_clone = item_height.clone();
3043 let view = cx.update(|_, cx| {
3044 cx.new(|_| TestView {
3045 state: state_clone,
3046 item_height: item_height_clone,
3047 })
3048 });
3049
3050 state.set_follow_mode(FollowMode::Tail);
3051
3052 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3055 view.clone().into_any_element()
3056 });
3057
3058 let offset = state.logical_scroll_top();
3061 assert_eq!(offset.item_ix, 6);
3062 assert_eq!(offset.offset_in_item, px(0.));
3063 assert!(state.is_following_tail());
3064
3065 item_height.set(80);
3068 state.remeasure();
3069
3070 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3071 view.into_any_element()
3072 });
3073
3074 let offset = state.logical_scroll_top();
3081 assert_eq!(offset.item_ix, 7);
3082 assert_eq!(offset.offset_in_item, px(40.));
3083 assert!(state.is_following_tail());
3084 }
3085
3086 #[gpui::test]
3087 fn test_pause_following_tail_reengages_when_still_at_bottom(cx: &mut TestAppContext) {
3088 let cx = cx.add_empty_window();
3089
3090 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3092
3093 struct TestView(ListState);
3094 impl Render for TestView {
3095 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3096 list(self.0.clone(), |_, _, _| {
3097 div().h(px(50.)).w_full().into_any()
3098 })
3099 .w_full()
3100 .h_full()
3101 }
3102 }
3103
3104 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3105 state.set_follow_mode(FollowMode::Tail);
3106
3107 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3108 view.clone().into_any_element()
3109 });
3110 assert!(state.is_following_tail());
3111
3112 state.pause_following_tail();
3116 assert!(!state.is_following_tail());
3117
3118 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3119 view.into_any_element()
3120 });
3121 assert!(
3122 state.is_following_tail(),
3123 "pausing while at the bottom must re-engage follow-tail on the next layout"
3124 );
3125 }
3126
3127 #[gpui::test]
3128 fn test_pause_following_tail_freezes_off_bottom(cx: &mut TestAppContext) {
3129 let cx = cx.add_empty_window();
3130
3131 let item_height = Rc::new(Cell::new(50usize));
3134 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3135
3136 struct TestView {
3137 state: ListState,
3138 item_height: Rc<Cell<usize>>,
3139 }
3140 impl Render for TestView {
3141 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3142 let height = self.item_height.get();
3143 list(self.state.clone(), move |_, _, _| {
3144 div().h(px(height as f32)).w_full().into_any()
3145 })
3146 .w_full()
3147 .h_full()
3148 }
3149 }
3150
3151 let view = cx.update(|_, cx| {
3152 cx.new(|_| TestView {
3153 state: state.clone(),
3154 item_height: item_height.clone(),
3155 })
3156 });
3157 state.set_follow_mode(FollowMode::Tail);
3158
3159 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3161 view.clone().into_any_element()
3162 });
3163 assert_eq!(state.logical_scroll_top().item_ix, 6);
3164 assert!(state.is_following_tail());
3165
3166 state.pause_following_tail();
3170 item_height.set(80);
3171 state.remeasure();
3172 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3173 view.clone().into_any_element()
3174 });
3175 let offset = state.logical_scroll_top();
3176 assert_eq!(offset.item_ix, 6);
3177 assert_eq!(offset.offset_in_item, px(0.));
3178 assert!(
3179 !state.is_following_tail(),
3180 "a paused list must not re-engage while the frozen top is off the bottom"
3181 );
3182
3183 item_height.set(50);
3186 state.remeasure();
3187 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3188 view.into_any_element()
3189 });
3190 assert!(
3191 state.is_following_tail(),
3192 "returning to the bottom must restore follow-tail"
3193 );
3194 }
3195
3196 #[gpui::test]
3197 fn test_follow_tail_disengages_on_user_scroll(cx: &mut TestAppContext) {
3198 let cx = cx.add_empty_window();
3199
3200 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3202
3203 struct TestView(ListState);
3204 impl Render for TestView {
3205 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3206 list(self.0.clone(), |_, _, _| {
3207 div().h(px(50.)).w_full().into_any()
3208 })
3209 .w_full()
3210 .h_full()
3211 }
3212 }
3213
3214 state.set_follow_mode(FollowMode::Tail);
3215
3216 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, cx| {
3218 cx.new(|_| TestView(state.clone())).into_any_element()
3219 });
3220 assert!(state.is_following_tail());
3221
3222 cx.simulate_event(ScrollEvent {
3225 position: point(px(50.), px(100.)),
3226 delta: ScrollDelta::Pixels(point(px(0.), px(100.))),
3227 ..Default::default()
3228 });
3229
3230 assert!(
3231 !state.is_following_tail(),
3232 "follow-tail should disengage when the user scrolls toward the start"
3233 );
3234 }
3235
3236 #[gpui::test]
3237 fn test_follow_tail_disengages_on_scrollbar_reposition(cx: &mut TestAppContext) {
3238 let cx = cx.add_empty_window();
3239
3240 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3242
3243 struct TestView(ListState);
3244 impl Render for TestView {
3245 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3246 list(self.0.clone(), |_, _, _| {
3247 div().h(px(50.)).w_full().into_any()
3248 })
3249 .w_full()
3250 .h_full()
3251 }
3252 }
3253
3254 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3255
3256 state.set_follow_mode(FollowMode::Tail);
3257
3258 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3260 view.clone().into_any_element()
3261 });
3262 assert!(state.is_following_tail());
3263
3264 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3266
3267 let offset = state.logical_scroll_top();
3268 assert_eq!(offset.item_ix, 3);
3269 assert_eq!(offset.offset_in_item, px(0.));
3270 assert!(
3271 !state.is_following_tail(),
3272 "follow-tail should disengage when the scrollbar manually repositions the list"
3273 );
3274
3275 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3278 view.into_any_element()
3279 });
3280
3281 let offset = state.logical_scroll_top();
3282 assert_eq!(offset.item_ix, 3);
3283 assert_eq!(offset.offset_in_item, px(0.));
3284 }
3285
3286 #[gpui::test]
3287 fn test_scrollbar_drag_with_growing_content(cx: &mut TestAppContext) {
3288 let cx = cx.add_empty_window();
3289
3290 let last_item_height = Rc::new(Cell::new(50usize));
3291 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3292
3293 struct TestView {
3294 state: ListState,
3295 last_item_height: Rc<Cell<usize>>,
3296 }
3297 impl Render for TestView {
3298 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3299 let last_item_height = self.last_item_height.clone();
3300 list(self.state.clone(), move |index, _, _| {
3301 let height = if index == 9 {
3302 last_item_height.get()
3303 } else {
3304 50
3305 };
3306 div().h(px(height as f32)).w_full().into_any()
3307 })
3308 .w_full()
3309 .h_full()
3310 }
3311 }
3312
3313 let view = cx.update(|_, cx| {
3314 cx.new(|_| TestView {
3315 state: state.clone(),
3316 last_item_height: last_item_height.clone(),
3317 })
3318 });
3319
3320 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3321 view.clone().into_any_element()
3322 });
3323
3324 state.scrollbar_drag_started();
3325
3326 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3327 let scrollbar_offset_before_growth = state.scroll_px_offset_for_scrollbar();
3328
3329 let offset = state.logical_scroll_top();
3330 assert_eq!(offset.item_ix, 3);
3331 assert_eq!(offset.offset_in_item, px(0.));
3332
3333 last_item_height.set(550);
3334 state.remeasure_items(9..10);
3335 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3336 view.clone().into_any_element()
3337 });
3338
3339 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
3340 assert_eq!(
3341 state.scroll_px_offset_for_scrollbar(),
3342 scrollbar_offset_before_growth
3343 );
3344
3345 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3346 let offset = state.logical_scroll_top();
3347 assert_eq!(offset.item_ix, 3);
3348 assert_eq!(offset.offset_in_item, px(0.));
3349 }
3350
3351 #[gpui::test]
3352 fn test_set_follow_tail_snaps_to_bottom(cx: &mut TestAppContext) {
3353 let cx = cx.add_empty_window();
3354
3355 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3357
3358 struct TestView(ListState);
3359 impl Render for TestView {
3360 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3361 list(self.0.clone(), |_, _, _| {
3362 div().h(px(50.)).w_full().into_any()
3363 })
3364 .w_full()
3365 .h_full()
3366 }
3367 }
3368
3369 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3370
3371 state.scroll_to(gpui::ListOffset {
3373 item_ix: 3,
3374 offset_in_item: px(0.),
3375 });
3376
3377 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3378 view.clone().into_any_element()
3379 });
3380
3381 let offset = state.logical_scroll_top();
3382 assert_eq!(offset.item_ix, 3);
3383 assert_eq!(offset.offset_in_item, px(0.));
3384 assert!(!state.is_following_tail());
3385
3386 state.set_follow_mode(FollowMode::Tail);
3389
3390 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3391 view.into_any_element()
3392 });
3393
3394 let offset = state.logical_scroll_top();
3397 assert_eq!(offset.item_ix, 6);
3398 assert_eq!(offset.offset_in_item, px(0.));
3399 assert!(state.is_following_tail());
3400 }
3401
3402 #[gpui::test]
3403 fn test_bottom_aligned_scrollbar_offset_at_end(cx: &mut TestAppContext) {
3404 let cx = cx.add_empty_window();
3405
3406 const ITEMS: usize = 10;
3407 const ITEM_SIZE: f32 = 50.0;
3408
3409 let state = ListState::new(
3410 ITEMS,
3411 crate::ListAlignment::Bottom,
3412 px(ITEMS as f32 * ITEM_SIZE),
3413 );
3414
3415 struct TestView(ListState);
3416 impl Render for TestView {
3417 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3418 list(self.0.clone(), |_, _, _| {
3419 div().h(px(ITEM_SIZE)).w_full().into_any()
3420 })
3421 .w_full()
3422 .h_full()
3423 }
3424 }
3425
3426 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
3427 cx.new(|_| TestView(state.clone())).into_any_element()
3428 });
3429
3430 assert_eq!(state.logical_scroll_top().item_ix, ITEMS);
3433
3434 let max_offset = state.max_offset_for_scrollbar();
3435 let scroll_offset = state.scroll_px_offset_for_scrollbar();
3436
3437 assert_eq!(
3438 -scroll_offset.y, max_offset.y,
3439 "scrollbar offset ({}) should equal max offset ({}) when list is pinned to bottom",
3440 -scroll_offset.y, max_offset.y,
3441 );
3442 }
3443
3444 #[gpui::test]
3448 fn test_follow_tail_reengages_when_scrolled_back_to_bottom(cx: &mut TestAppContext) {
3449 let cx = cx.add_empty_window();
3450
3451 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3453
3454 struct TestView(ListState);
3455 impl Render for TestView {
3456 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3457 list(self.0.clone(), |_, _, _| {
3458 div().h(px(50.)).w_full().into_any()
3459 })
3460 .w_full()
3461 .h_full()
3462 }
3463 }
3464
3465 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3466
3467 state.set_follow_mode(FollowMode::Tail);
3468
3469 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3470 view.clone().into_any_element()
3471 });
3472 assert!(state.is_following_tail());
3473
3474 cx.simulate_event(ScrollEvent {
3476 position: point(px(50.), px(100.)),
3477 delta: ScrollDelta::Pixels(point(px(0.), px(50.))),
3478 ..Default::default()
3479 });
3480 assert!(!state.is_following_tail());
3481
3482 cx.simulate_event(ScrollEvent {
3484 position: point(px(50.), px(100.)),
3485 delta: ScrollDelta::Pixels(point(px(0.), px(-10000.))),
3486 ..Default::default()
3487 });
3488
3489 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3492 view.clone().into_any_element()
3493 });
3494 assert!(
3495 state.is_following_tail(),
3496 "follow_tail should re-engage after scrolling back to the bottom"
3497 );
3498 }
3499
3500 #[gpui::test]
3503 fn test_follow_tail_reengagement_not_fooled_by_unmeasured_items(cx: &mut TestAppContext) {
3504 let cx = cx.add_empty_window();
3505
3506 let state = ListState::new(20, crate::ListAlignment::Top, px(1000.));
3510
3511 struct TestView(ListState);
3512 impl Render for TestView {
3513 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3514 list(self.0.clone(), |_, _, _| {
3515 div().h(px(50.)).w_full().into_any()
3516 })
3517 .w_full()
3518 .h_full()
3519 }
3520 }
3521
3522 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3523
3524 state.set_follow_mode(FollowMode::Tail);
3525
3526 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3527 view.clone().into_any_element()
3528 });
3529 assert!(state.is_following_tail());
3530
3531 cx.simulate_event(ScrollEvent {
3535 position: point(px(50.), px(100.)),
3536 delta: ScrollDelta::Pixels(point(px(0.), px(200.))),
3537 ..Default::default()
3538 });
3539 assert!(!state.is_following_tail());
3540
3541 state.remeasure_items(19..20);
3545
3546 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3552 view.clone().into_any_element()
3553 });
3554 assert!(
3555 !state.is_following_tail(),
3556 "follow_tail should not falsely re-engage due to an unmeasured item \
3557 reducing items.summary().height"
3558 );
3559 }
3560
3561 #[gpui::test]
3562 fn test_follow_tail_reengages_after_scrollbar_disengagement(cx: &mut TestAppContext) {
3563 let cx = cx.add_empty_window();
3564
3565 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3567
3568 struct TestView(ListState);
3569 impl Render for TestView {
3570 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3571 list(self.0.clone(), |_, _, _| {
3572 div().h(px(50.)).w_full().into_any()
3573 })
3574 .w_full()
3575 .h_full()
3576 }
3577 }
3578
3579 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3580
3581 state.set_follow_mode(FollowMode::Tail);
3582 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3583 view.clone().into_any_element()
3584 });
3585 assert!(state.is_following_tail());
3586
3587 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3589 assert!(!state.is_following_tail());
3590
3591 state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
3594 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3595 view.into_any_element()
3596 });
3597 assert!(
3598 state.is_following_tail(),
3599 "follow_tail should re-engage after scrolling back to the bottom via the scrollbar"
3600 );
3601 }
3602
3603 #[gpui::test]
3604 fn test_follow_tail_reengages_after_scrollbar_drag_to_bottom_while_growing(
3605 cx: &mut TestAppContext,
3606 ) {
3607 let cx = cx.add_empty_window();
3608
3609 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3610
3611 struct TestView(ListState);
3612 impl Render for TestView {
3613 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3614 list(self.0.clone(), |_, _, _| {
3615 div().h(px(50.)).w_full().into_any()
3616 })
3617 .w_full()
3618 .h_full()
3619 }
3620 }
3621
3622 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3623
3624 state.set_follow_mode(FollowMode::Tail);
3625 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3626 view.clone().into_any_element()
3627 });
3628 assert!(state.is_following_tail());
3629
3630 state.scrollbar_drag_started();
3631
3632 state.splice(10..10, 10);
3633 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3634 view.clone().into_any_element()
3635 });
3636
3637 state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
3638 state.scrollbar_drag_ended();
3639
3640 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3641 view.into_any_element()
3642 });
3643
3644 assert!(
3645 state.is_following_tail(),
3646 "follow_tail should re-engage when the user drags the scrollbar to \
3647 the bottom of its track, even when content has grown during the drag \
3648 (so frozen_bottom < live_bottom)"
3649 );
3650 }
3651
3652 fn draw_list(
3653 state: &ListState,
3654 viewport_height: f32,
3655 render_item: impl Fn(usize) -> AnyElement + 'static,
3656 cx: &mut VisualTestContext,
3657 ) {
3658 cx.draw(
3659 point(px(0.), px(0.)),
3660 size(px(100.), px(viewport_height)),
3661 |_, cx| {
3662 cx.new(|_| TestView {
3663 state: state.clone(),
3664 render_item: Rc::new(render_item),
3665 })
3666 .into_any_element()
3667 },
3668 );
3669 }
3670
3671 fn painted_item(
3672 index: usize,
3673 height: f32,
3674 painted: &Rc<RefCell<Vec<(usize, Pixels, Pixels)>>>,
3675 ) -> AnyElement {
3676 let painted = painted.clone();
3677 canvas(
3678 |_, _, _| {},
3679 move |bounds, _, _, _| {
3680 painted
3681 .borrow_mut()
3682 .push((index, bounds.top(), bounds.bottom()));
3683 },
3684 )
3685 .h(px(height))
3686 .w_full()
3687 .into_any()
3688 }
3689
3690 fn item_readiness(state: &ListState, ready: bool) -> Rc<Cell<bool>> {
3691 let ready = Rc::new(Cell::new(ready));
3692 state.set_item_measurement_readiness({
3693 let ready = ready.clone();
3694 move |_, _| ready.get()
3695 });
3696 ready
3697 }
3698
3699 fn list_offset(item_ix: usize, offset: f32) -> ListOffset {
3700 ListOffset {
3701 item_ix,
3702 offset_in_item: px(offset),
3703 }
3704 }
3705
3706 struct TestView {
3707 state: ListState,
3708 render_item: Rc<dyn Fn(usize) -> AnyElement>,
3709 }
3710
3711 impl Render for TestView {
3712 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3713 let render_item = self.render_item.clone();
3714 list(self.state.clone(), move |index, _, _| render_item(index))
3715 .w_full()
3716 .h_full()
3717 }
3718 }
3719
3720 struct TestListView(ListState);
3721 impl Render for TestListView {
3722 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3723 list(self.0.clone(), |_, _, _| {
3724 div().h(px(20.)).w_full().into_any()
3725 })
3726 .w_full()
3727 .h_full()
3728 }
3729 }
3730}