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