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