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