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 scroll_handler: Option<Box<dyn FnMut(&ListScrollEvent, &mut Window, &mut App)>>,
71 scrollbar_drag_start_height: Option<Pixels>,
72 measuring_behavior: ListMeasuringBehavior,
73 item_measurement_ready: Option<Box<dyn Fn(usize, &App) -> bool>>,
74 follow_state: FollowState,
75}
76
77#[derive(Clone, Copy)]
78struct ScrollAnchor {
79 position: ListOffset,
80 pending: Option<PendingScroll>,
81 provisional: bool,
82 pending_end: bool,
83}
84
85#[derive(Clone, Copy)]
86enum PendingScroll {
87 Absolute(Pixels),
88 Proportional(f32),
89}
90
91enum ScrollAnchorMode {
92 Absolute,
93 Proportional,
94}
95
96#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
98pub enum FollowMode {
99 #[default]
101 Normal,
102 Tail,
104}
105
106#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
107enum FollowState {
108 #[default]
109 Normal,
110 Tail {
111 is_following: bool,
112 },
113}
114
115impl FollowState {
116 fn is_following(&self) -> bool {
117 matches!(self, FollowState::Tail { is_following: true })
118 }
119
120 fn has_stopped_following(&self) -> bool {
121 matches!(
122 self,
123 FollowState::Tail {
124 is_following: false
125 }
126 )
127 }
128
129 fn start_following(&mut self) {
130 if let FollowState::Tail {
131 is_following: false,
132 } = self
133 {
134 *self = FollowState::Tail { is_following: true };
135 }
136 }
137
138 fn stop_following(&mut self) {
139 if let FollowState::Tail { is_following: true } = self {
140 *self = FollowState::Tail {
141 is_following: false,
142 };
143 }
144 }
145}
146
147#[derive(Clone, Copy, Debug, Eq, PartialEq)]
149pub enum ListAlignment {
150 Top,
152 Bottom,
154}
155
156pub struct ListScrollEvent {
158 pub visible_range: Range<usize>,
160
161 pub count: usize,
163
164 pub is_scrolled: bool,
166
167 pub is_following_tail: bool,
169}
170
171#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
173pub enum ListSizingBehavior {
174 Infer,
176 #[default]
178 Auto,
179}
180
181#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
183pub enum ListMeasuringBehavior {
184 Measure(bool),
187 #[default]
189 Visible,
190}
191
192impl ListMeasuringBehavior {
193 fn reset(&mut self) {
194 match self {
195 ListMeasuringBehavior::Measure(has_measured) => *has_measured = false,
196 ListMeasuringBehavior::Visible => {}
197 }
198 }
199}
200
201#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
203pub enum ListHorizontalSizingBehavior {
204 #[default]
206 FitList,
207 Unconstrained,
209}
210
211struct LayoutItemsResponse {
212 max_item_width: Pixels,
213 scroll_top: ListOffset,
214 item_layouts: VecDeque<ItemLayout>,
215}
216
217struct ItemLayout {
218 index: usize,
219 element: AnyElement,
220 size: Size<Pixels>,
221}
222
223pub struct ListPrepaintState {
225 hitbox: Hitbox,
226 layout: LayoutItemsResponse,
227}
228
229#[derive(Clone)]
230enum ListItem {
231 Unmeasured {
232 size_hint: Option<Size<Pixels>>,
233 focus_handle: Option<FocusHandle>,
234 },
235 Measured {
236 size: Size<Pixels>,
237 focus_handle: Option<FocusHandle>,
238 },
239}
240
241impl ListItem {
242 fn with_measurement(&self, size: Size<Pixels>, ready: bool) -> Self {
243 if ready {
244 Self::Measured {
245 size,
246 focus_handle: self.focus_handle(),
247 }
248 } else {
249 Self::Unmeasured {
250 size_hint: Some(size),
251 focus_handle: self.focus_handle(),
252 }
253 }
254 }
255
256 fn size(&self) -> Option<Size<Pixels>> {
257 if let ListItem::Measured { size, .. } = self {
258 Some(*size)
259 } else {
260 None
261 }
262 }
263
264 fn size_hint(&self) -> Option<Size<Pixels>> {
265 match self {
266 ListItem::Measured { size, .. } => Some(*size),
267 ListItem::Unmeasured { size_hint, .. } => *size_hint,
268 }
269 }
270
271 fn focus_handle(&self) -> Option<FocusHandle> {
272 match self {
273 ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
274 focus_handle.clone()
275 }
276 }
277 }
278
279 fn contains_focused(&self, window: &Window, cx: &App) -> bool {
280 match self {
281 ListItem::Unmeasured { focus_handle, .. } | ListItem::Measured { focus_handle, .. } => {
282 focus_handle
283 .as_ref()
284 .is_some_and(|handle| handle.contains_focused(window, cx))
285 }
286 }
287 }
288}
289
290#[derive(Clone, Debug, Default, PartialEq)]
291struct ListItemSummary {
292 count: usize,
293 rendered_count: usize,
294 unrendered_count: usize,
295 height: Pixels,
296 has_focus_handles: bool,
297 has_unknown_height: bool,
298}
299
300#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
301struct Count(usize);
302
303#[derive(Clone, Debug, Default)]
304struct Height(Pixels);
305
306impl ListState {
307 pub fn new(item_count: usize, alignment: ListAlignment, overdraw: Pixels) -> Self {
314 let state = Self(Rc::new(RefCell::new(StateInner {
315 last_layout_bounds: None,
316 last_padding: None,
317 items: SumTree::default(),
318 scroll_anchor: None,
319 alignment,
320 overdraw,
321 scroll_handler: None,
322 reset: false,
323 scrollbar_drag_start_height: None,
324 measuring_behavior: ListMeasuringBehavior::default(),
325 item_measurement_ready: None,
326 follow_state: FollowState::default(),
327 })));
328 state.splice(0..0, item_count);
329 state
330 }
331
332 pub fn measure_all(self) -> Self {
336 self.0.borrow_mut().measuring_behavior = ListMeasuringBehavior::Measure(false);
337 self
338 }
339
340 pub fn with_uniform_item_height(self, height: Pixels) -> Self {
347 self.apply_uniform_item_height(height);
348 self
349 }
350
351 pub fn reset(&self, element_count: usize) {
355 let old_count = {
356 let state = &mut *self.0.borrow_mut();
357 state.reset = true;
358 state.measuring_behavior.reset();
359 state.set_scroll_anchor(None);
360 state.scrollbar_drag_start_height = None;
361 state.items.summary().count
362 };
363
364 self.splice(0..old_count, element_count);
365 }
366
367 pub fn reset_with_uniform_height(&self, element_count: usize, height: Pixels) {
371 self.reset(element_count);
372 self.apply_uniform_item_height(height);
373 }
374
375 fn apply_uniform_item_height(&self, height: Pixels) {
376 let size_hint = Size {
377 width: px(0.),
378 height,
379 };
380 let mut state = self.0.borrow_mut();
381 let new_items = state
382 .items
383 .iter()
384 .map(|item| ListItem::Unmeasured {
385 size_hint: Some(item.size_hint().unwrap_or(size_hint)),
386 focus_handle: item.focus_handle(),
387 })
388 .collect::<Vec<_>>();
389 let mut tree = SumTree::default();
390 tree.extend(new_items, ());
391 state.items = tree;
392 }
393
394 pub fn remeasure(&self) {
399 let count = self.item_count();
400 self.remeasure_items_with_scroll_anchor(0..count, ScrollAnchorMode::Proportional);
401 }
402
403 pub fn remeasure_items(&self, range: Range<usize>) {
411 self.remeasure_items_with_scroll_anchor(range, ScrollAnchorMode::Absolute);
412 }
413
414 fn remeasure_items_with_scroll_anchor(&self, range: Range<usize>, mode: ScrollAnchorMode) {
415 let state = &mut *self.0.borrow_mut();
416
417 if let Some(anchor) = state.scroll_anchor.as_mut()
418 && range.contains(&anchor.position.item_ix)
419 {
420 anchor.pending = match mode {
421 ScrollAnchorMode::Absolute => {
422 Some(PendingScroll::Absolute(anchor.position.offset_in_item))
423 }
424 ScrollAnchorMode::Proportional => {
425 let mut cursor = state.items.cursor::<Count>(());
426 cursor.seek(&Count(anchor.position.item_ix), Bias::Right);
427 cursor
428 .item()
429 .and_then(|item| item.size())
430 .map(|size| {
431 let fraction = if size.height > px(0.) {
432 (anchor.position.offset_in_item / size.height).clamp(0., 1.)
433 } else {
434 0.
435 };
436 PendingScroll::Proportional(fraction)
437 })
438 .or(anchor.pending)
439 }
440 };
441 }
442
443 let new_items = {
446 let mut cursor = state.items.cursor::<Count>(());
447 let mut new_items = cursor.slice(&Count(range.start), Bias::Right);
448 let invalidated = cursor.slice(&Count(range.end), Bias::Right);
449 new_items.extend(
450 invalidated.iter().map(|item| ListItem::Unmeasured {
451 size_hint: item.size_hint(),
452 focus_handle: item.focus_handle(),
453 }),
454 (),
455 );
456 new_items.append(cursor.suffix(), ());
457 new_items
458 };
459 state.items = new_items;
460 state.measuring_behavior.reset();
461 }
462
463 pub fn item_count(&self) -> usize {
465 self.0.borrow().items.summary().count
466 }
467
468 pub fn is_scrolled_to_end(&self) -> Option<bool> {
471 let state = self.0.borrow();
472 let bounds = state.last_layout_bounds?;
473 let summary = state.items.summary();
474 if summary.has_unknown_height {
475 return None;
476 }
477 let padding = state.last_padding.unwrap_or_default();
478 let content_height = summary.height + padding.top + padding.bottom;
479 let scroll_max = (content_height - bounds.size.height).max(px(0.));
480 if scroll_max <= px(0.) {
481 return None;
482 }
483 let scroll_top = state.scroll_top(&state.logical_scroll_top());
484 Some(scroll_top >= scroll_max)
485 }
486
487 pub fn splice(&self, old_range: Range<usize>, count: usize) {
490 self.splice_focusable(old_range, (0..count).map(|_| None))
491 }
492
493 pub fn splice_focusable(
498 &self,
499 old_range: Range<usize>,
500 focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
501 ) {
502 let state = &mut *self.0.borrow_mut();
503
504 let mut old_items = state.items.cursor::<Count>(());
505 let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right);
506 old_items.seek_forward(&Count(old_range.end), Bias::Right);
507
508 let mut spliced_count = 0;
509 new_items.extend(
510 focus_handles.into_iter().map(|focus_handle| {
511 spliced_count += 1;
512 ListItem::Unmeasured {
513 size_hint: None,
514 focus_handle,
515 }
516 }),
517 (),
518 );
519 new_items.append(old_items.suffix(), ());
520 drop(old_items);
521 state.items = new_items;
522
523 if let Some(anchor) = state.scroll_anchor.as_mut() {
524 if anchor.provisional && old_range.start <= anchor.position.item_ix {
525 anchor.provisional = false;
526 anchor.pending = None;
527 }
528 if old_range.contains(&anchor.position.item_ix) {
529 anchor.position = ListOffset {
530 item_ix: old_range.start,
531 offset_in_item: px(0.),
532 };
533 anchor.pending = None;
534 } else if old_range.end <= anchor.position.item_ix {
535 anchor.position.item_ix = anchor.position.item_ix - old_range.len() + spliced_count;
536 }
537 }
538 }
539
540 pub fn set_scroll_handler(
542 &self,
543 handler: impl FnMut(&ListScrollEvent, &mut Window, &mut App) + 'static,
544 ) {
545 self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
546 }
547
548 pub fn logical_scroll_top(&self) -> ListOffset {
550 self.0.borrow().logical_scroll_top()
551 }
552
553 pub fn scroll_by(&self, distance: Pixels) {
555 if distance == px(0.) {
556 return;
557 }
558
559 let current_offset = self.logical_scroll_top();
560 let state = &mut *self.0.borrow_mut();
561
562 if distance < px(0.) {
563 state.follow_state.stop_following();
564 }
565
566 let mut cursor = state.items.cursor::<ListItemSummary>(());
567 cursor.seek(&Count(current_offset.item_ix), Bias::Right);
568
569 let start_pixel_offset = cursor.start().height + current_offset.offset_in_item;
570 let new_pixel_offset = (start_pixel_offset + distance).max(px(0.));
571 if new_pixel_offset > start_pixel_offset {
572 cursor.seek_forward(&Height(new_pixel_offset), Bias::Right);
573 } else {
574 cursor.seek(&Height(new_pixel_offset), Bias::Right);
575 }
576
577 let scroll_top = ListOffset {
578 item_ix: cursor.start().count,
579 offset_in_item: new_pixel_offset - cursor.start().height,
580 };
581 drop(cursor);
582 state.set_scroll_anchor(Some(scroll_top));
583 }
584
585 pub fn scroll_to_end(&self) {
592 let state = &mut *self.0.borrow_mut();
593 let item_count = state.items.summary().count;
594 state.set_scroll_anchor(Some(ListOffset {
595 item_ix: item_count,
596 offset_in_item: px(0.),
597 }));
598 }
599
600 pub fn set_follow_mode(&self, mode: FollowMode) {
605 if mode == FollowMode::Normal {
606 self.pause_following_tail();
607 }
608 let state = &mut *self.0.borrow_mut();
609
610 match mode {
611 FollowMode::Normal => {
612 state.follow_state = FollowState::Normal;
613 }
614 FollowMode::Tail => {
615 state.follow_state = FollowState::Tail { is_following: true };
616 if matches!(mode, FollowMode::Tail) {
617 let item_count = state.items.summary().count;
618 state.set_scroll_anchor(Some(ListOffset {
619 item_ix: item_count,
620 offset_in_item: px(0.),
621 }));
622 }
623 }
624 }
625 }
626
627 pub fn pause_following_tail(&self) {
637 let state = &mut *self.0.borrow_mut();
638 if state.follow_state.is_following()
639 && let Some(anchor) = state.scroll_anchor.as_mut()
640 {
641 anchor.pending_end = false;
642 }
643 state.follow_state.stop_following();
644 }
645
646 pub fn set_item_measurement_readiness(&self, ready: impl Fn(usize, &App) -> bool + 'static) {
650 self.0.borrow_mut().item_measurement_ready = Some(Box::new(ready));
651 }
652
653 pub fn is_following_tail(&self) -> bool {
656 matches!(
657 self.0.borrow().follow_state,
658 FollowState::Tail { is_following: true }
659 )
660 }
661
662 pub fn scroll_to(&self, mut scroll_top: ListOffset) {
664 let state = &mut *self.0.borrow_mut();
665 let item_count = state.items.summary().count;
666 if scroll_top.item_ix >= item_count {
667 scroll_top.item_ix = item_count;
668 scroll_top.offset_in_item = px(0.);
669 }
670
671 if scroll_top.item_ix < item_count {
672 state.follow_state.stop_following();
673 }
674
675 state.set_scroll_anchor(Some(scroll_top));
676 }
677
678 pub fn scroll_to_reveal_item(&self, ix: usize) {
680 let state = &mut *self.0.borrow_mut();
681
682 let mut scroll_top = state.logical_scroll_top();
683 let height = state
684 .last_layout_bounds
685 .map_or(px(0.), |bounds| bounds.size.height);
686 let padding = state.last_padding.unwrap_or_default();
687
688 if ix <= scroll_top.item_ix {
689 scroll_top.item_ix = ix;
690 scroll_top.offset_in_item = px(0.);
691 } else {
692 let mut cursor = state.items.cursor::<ListItemSummary>(());
693 cursor.seek(&Count(ix + 1), Bias::Right);
694 let bottom = cursor.start().height + padding.top;
695 let goal_top = px(0.).max(bottom - height + padding.bottom);
696
697 cursor.seek(&Height(goal_top), Bias::Left);
698 let start_ix = cursor.start().count;
699 let start_item_top = cursor.start().height;
700
701 if start_ix >= scroll_top.item_ix {
702 scroll_top.item_ix = start_ix;
703 scroll_top.offset_in_item = goal_top - start_item_top;
704 }
705 }
706
707 state.set_scroll_anchor(Some(scroll_top));
708 }
709
710 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
713 let state = &*self.0.borrow();
714
715 let bounds = state.last_layout_bounds.unwrap_or_default();
716 let padding = state.last_padding.unwrap_or_default();
717 let scroll_top = state.logical_scroll_top();
718 if ix < scroll_top.item_ix {
719 return None;
720 }
721
722 let mut cursor = state.items.cursor::<Dimensions<Count, Height>>(());
723 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
724
725 let scroll_top = cursor.start().1.0 + scroll_top.offset_in_item;
726
727 cursor.seek_forward(&Count(ix), Bias::Right);
728 if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
729 let &Dimensions(Count(count), Height(top), _) = cursor.start();
730 if count == ix {
731 let top = bounds.top() + top - scroll_top;
732 return Some(Bounds::from_corners(
733 point(bounds.left() + padding.left, top),
734 point(bounds.right() - padding.right, top + size.height),
735 ));
736 }
737 }
738 None
739 }
740
741 pub fn scrollbar_drag_started(&self) {
746 let mut state = self.0.borrow_mut();
747 state.scrollbar_drag_start_height = Some(state.items.summary().height);
748 }
749
750 pub fn scrollbar_drag_ended(&self) {
754 self.0.borrow_mut().scrollbar_drag_start_height.take();
755 }
756
757 pub fn is_scrollbar_dragging(&self) -> bool {
764 self.0.borrow().scrollbar_drag_start_height.is_some()
765 }
766
767 pub fn set_offset_from_scrollbar(&self, point: Point<Pixels>) {
769 self.0.borrow_mut().set_offset_from_scrollbar(point);
770 }
771
772 pub fn max_offset_for_scrollbar(&self) -> Point<Pixels> {
775 let state = self.0.borrow();
776 point(Pixels::ZERO, state.max_scroll_offset())
777 }
778
779 pub fn scroll_px_offset_for_scrollbar(&self) -> Point<Pixels> {
784 let state = &self.0.borrow();
785
786 if state.scroll_anchor.is_none() && state.alignment == ListAlignment::Bottom {
787 return Point::new(px(0.), -state.max_scroll_offset());
788 }
789
790 let logical_scroll_top = state.logical_scroll_top();
791
792 let mut cursor = state.items.cursor::<ListItemSummary>(());
793 let summary: ListItemSummary =
794 cursor.summary(&Count(logical_scroll_top.item_ix), Bias::Right);
795 let offset = summary.height + logical_scroll_top.offset_in_item;
796
797 Point::new(px(0.), -offset)
798 }
799
800 pub fn viewport_bounds(&self) -> Bounds<Pixels> {
802 self.0.borrow().last_layout_bounds.unwrap_or_default()
803 }
804
805 pub fn item_is_above_viewport(&self, ix: usize) -> Option<bool> {
813 let viewport_bounds = self.0.borrow().last_layout_bounds?;
814
815 let scroll_top = self.logical_scroll_top();
816 if ix < scroll_top.item_ix {
817 return Some(true);
820 }
821
822 let item_bounds = self.bounds_for_item(ix)?;
823 Some(item_bounds.bottom() <= viewport_bounds.top())
824 }
825
826 pub fn item_is_below_viewport(&self, ix: usize) -> Option<bool> {
832 let viewport_bounds = self.0.borrow().last_layout_bounds?;
833
834 let scroll_top = self.logical_scroll_top();
835 if ix < scroll_top.item_ix {
836 return Some(false);
839 }
840
841 let item_bounds = self.bounds_for_item(ix)?;
842 Some(item_bounds.top() >= viewport_bounds.bottom())
843 }
844}
845
846impl StateInner {
847 fn max_scroll_offset(&self) -> Pixels {
848 let bounds = self.last_layout_bounds.unwrap_or_default();
849 let height = self
850 .scrollbar_drag_start_height
851 .unwrap_or_else(|| self.items.summary().height);
852 (height - bounds.size.height).max(px(0.))
853 }
854
855 fn visible_range(
856 items: &SumTree<ListItem>,
857 height: Pixels,
858 scroll_top: &ListOffset,
859 ) -> Range<usize> {
860 let mut cursor = items.cursor::<ListItemSummary>(());
861 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
862 let start_y = cursor.start().height + scroll_top.offset_in_item;
863 cursor.seek_forward(&Height(start_y + height), Bias::Left);
864 scroll_top.item_ix..cursor.start().count + 1
865 }
866
867 fn scroll(
868 &mut self,
869 scroll_top: &ListOffset,
870 height: Pixels,
871 delta: Point<Pixels>,
872 current_view: EntityId,
873 window: &mut Window,
874 cx: &mut App,
875 ) {
876 if self.reset || delta.y == px(0.) {
879 return;
880 }
881
882 let padding = self.last_padding.unwrap_or_default();
883 let scroll_max =
884 (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
885 let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
886 .max(px(0.))
887 .min(scroll_max);
888
889 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
890 self.set_scroll_anchor(None);
891 } else {
892 let (start, ..) =
893 self.items
894 .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
895 let scroll_top = ListOffset {
896 item_ix: start.count,
897 offset_in_item: new_scroll_top - start.height,
898 };
899 self.set_scroll_anchor(Some(scroll_top));
900 }
901
902 if delta.y > px(0.) {
903 self.follow_state.stop_following();
904 }
905
906 if let Some(handler) = self.scroll_handler.as_mut() {
907 let visible_range = Self::visible_range(&self.items, height, scroll_top);
908 handler(
909 &ListScrollEvent {
910 visible_range,
911 count: self.items.summary().count,
912 is_scrolled: self.scroll_anchor.is_some(),
913 is_following_tail: matches!(
914 self.follow_state,
915 FollowState::Tail { is_following: true }
916 ),
917 },
918 window,
919 cx,
920 );
921 }
922
923 cx.notify(current_view);
924 }
925
926 fn logical_scroll_top(&self) -> ListOffset {
927 self.scroll_anchor
928 .map(|anchor| anchor.position)
929 .unwrap_or_else(|| match self.alignment {
930 ListAlignment::Top => ListOffset {
931 item_ix: 0,
932 offset_in_item: px(0.),
933 },
934 ListAlignment::Bottom => ListOffset {
935 item_ix: self.items.summary().count,
936 offset_in_item: px(0.),
937 },
938 })
939 }
940
941 fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
942 let (start, ..) = self.items.find::<ListItemSummary, _>(
943 (),
944 &Count(logical_scroll_top.item_ix),
945 Bias::Right,
946 );
947 start.height + logical_scroll_top.offset_in_item
948 }
949
950 fn is_item_ready(&self, index: usize, cx: &App) -> bool {
951 self.item_measurement_ready
952 .as_ref()
953 .is_none_or(|ready| ready(index, cx))
954 }
955
956 fn is_provisional(&self) -> bool {
957 self.scroll_anchor.is_some_and(|anchor| anchor.provisional)
958 }
959
960 fn set_scroll_anchor(&mut self, position: Option<ListOffset>) {
961 let Some(position) = position else {
962 self.scroll_anchor = None;
963 return;
964 };
965 let pending = self
966 .scroll_anchor
967 .and_then(|anchor| anchor.pending)
968 .filter(|_| position.item_ix < self.items.summary().count)
969 .and_then(|pending| match (pending, self.is_provisional()) {
970 (PendingScroll::Absolute(_), _) | (_, true) => {
971 Some(PendingScroll::Absolute(position.offset_in_item))
972 }
973 (PendingScroll::Proportional(_), false) => {
974 let mut cursor = self.items.cursor::<Count>(());
975 cursor.seek(&Count(position.item_ix), Bias::Right);
976 cursor
977 .item()
978 .and_then(|item| item.size_hint())
979 .filter(|size| size.height > px(0.))
980 .map(|size| {
981 PendingScroll::Proportional(
982 (position.offset_in_item / size.height).clamp(0., 1.),
983 )
984 })
985 }
986 });
987 self.scroll_anchor = Some(ScrollAnchor {
988 position,
989 pending,
990 provisional: false,
991 pending_end: false,
992 });
993 }
994
995 fn layout_all_items(
996 &mut self,
997 available_width: Pixels,
998 render_item: &mut RenderItemFn,
999 window: &mut Window,
1000 cx: &mut App,
1001 ) {
1002 match &mut self.measuring_behavior {
1003 ListMeasuringBehavior::Visible => {
1004 return;
1005 }
1006 ListMeasuringBehavior::Measure(has_measured) => {
1007 if *has_measured {
1008 return;
1009 }
1010 *has_measured = true;
1011 }
1012 }
1013
1014 let cursor = self.items.cursor::<Count>(());
1015 let available_item_space = size(
1016 AvailableSpace::Definite(available_width),
1017 AvailableSpace::MinContent,
1018 );
1019
1020 let mut measured_items = Vec::default();
1021
1022 for (ix, item) in cursor.enumerate() {
1023 let size = item.size().unwrap_or_else(|| {
1024 let mut element = render_item(ix, window, cx);
1025 element.layout_as_root(available_item_space, window, cx)
1026 });
1027
1028 measured_items.push(item.with_measurement(size, self.is_item_ready(ix, cx)));
1029 }
1030
1031 self.items = SumTree::from_iter(measured_items, ());
1032 self.measuring_behavior =
1033 ListMeasuringBehavior::Measure(self.items.summary().unrendered_count == 0);
1034 }
1035
1036 fn layout_items(
1037 &mut self,
1038 available_width: Option<Pixels>,
1039 available_height: Pixels,
1040 padding: &Edges<Pixels>,
1041 render_item: &mut RenderItemFn,
1042 window: &mut Window,
1043 cx: &mut App,
1044 ) -> LayoutItemsResponse {
1045 let old_items = self.items.clone();
1046 let mut measured_items = VecDeque::new();
1047 let mut item_layouts = VecDeque::new();
1048 let mut rendered_height = padding.top;
1049 let mut max_item_width = px(0.);
1050 let mut scroll_top = self.logical_scroll_top();
1051
1052 if self.follow_state.is_following()
1053 || self.scroll_anchor.is_some_and(|anchor| anchor.pending_end)
1054 {
1055 scroll_top = ListOffset {
1056 item_ix: self.items.summary().count,
1057 offset_in_item: px(0.),
1058 };
1059 self.set_scroll_anchor(Some(scroll_top));
1060 }
1061
1062 let preserve_anchor = scroll_top.item_ix < self.items.summary().count;
1063 if !preserve_anchor {
1064 self.follow_state.start_following();
1065 }
1066 let mut provisional = false;
1067 let mut rendered_focused_item = false;
1068
1069 let available_item_space = size(
1070 available_width.map_or(AvailableSpace::MaxContent, |width| {
1071 AvailableSpace::Definite(width)
1072 }),
1073 AvailableSpace::MinContent,
1074 );
1075
1076 let mut cursor = old_items.cursor::<Count>(());
1077
1078 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1080 for (ix, item) in cursor.by_ref().enumerate() {
1081 let visible_height = rendered_height - scroll_top.offset_in_item;
1082 if visible_height >= available_height + self.overdraw {
1083 break;
1084 }
1085
1086 let item_index = scroll_top.item_ix + ix;
1087 let (size, ready) = if visible_height >= available_height
1088 && let Some(size) = item.size()
1089 {
1090 (size, self.is_item_ready(item_index, cx))
1091 } else {
1092 let mut element = render_item(item_index, window, cx);
1093 let element_size = element.layout_as_root(available_item_space, window, cx);
1094 let ready = self.is_item_ready(item_index, cx);
1095 if ix == 0
1096 && ready
1097 && let Some(anchor) = self.scroll_anchor.as_mut()
1098 && let Some(pending) = anchor.pending.take()
1099 {
1100 scroll_top.offset_in_item = match pending {
1101 PendingScroll::Absolute(offset) => offset.min(element_size.height),
1102 PendingScroll::Proportional(fraction) => element_size.height * fraction,
1103 };
1104 anchor.position = scroll_top;
1105 }
1106
1107 if visible_height < available_height {
1108 item_layouts.push_back(ItemLayout {
1109 index: item_index,
1110 element,
1111 size: element_size,
1112 });
1113 if item.contains_focused(window, cx) {
1114 rendered_focused_item = true;
1115 }
1116 }
1117 (element_size, ready)
1118 };
1119
1120 rendered_height += size.height;
1121 max_item_width = max_item_width.max(size.width);
1122 provisional |= !ready;
1123 measured_items.push_back(item.with_measurement(size, ready));
1124 if !ready && visible_height >= available_height {
1125 break;
1126 }
1127 }
1128 rendered_height += padding.bottom;
1129
1130 cursor.seek(&Count(scroll_top.item_ix), Bias::Right);
1132
1133 if !provisional && rendered_height - scroll_top.offset_in_item < available_height {
1136 let forward_layout_count = item_layouts.len();
1137 let forward_focused = rendered_focused_item;
1138 while rendered_height < available_height {
1139 cursor.prev();
1140 if let Some(item) = cursor.item() {
1141 let item_index = cursor.start().0;
1142 let mut element = render_item(item_index, window, cx);
1143 let element_size = element.layout_as_root(available_item_space, window, cx);
1144 let ready = self.is_item_ready(item_index, cx);
1145 provisional |= !ready;
1146 rendered_height += element_size.height;
1147 measured_items.push_front(item.with_measurement(element_size, ready));
1148 item_layouts.push_front(ItemLayout {
1149 index: item_index,
1150 element,
1151 size: element_size,
1152 });
1153 if item.contains_focused(window, cx) {
1154 rendered_focused_item = true;
1155 }
1156 if preserve_anchor && provisional {
1157 break;
1158 }
1159 } else {
1160 break;
1161 }
1162 }
1163
1164 if preserve_anchor && provisional {
1165 item_layouts.drain(..item_layouts.len() - forward_layout_count);
1166 rendered_focused_item = forward_focused;
1167 } else {
1168 scroll_top = ListOffset {
1169 item_ix: cursor.start().0,
1170 offset_in_item: rendered_height - available_height,
1171 };
1172
1173 match self.alignment {
1174 ListAlignment::Top => {
1175 scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
1176 self.set_scroll_anchor(Some(scroll_top));
1177 }
1178 ListAlignment::Bottom => {
1179 scroll_top = ListOffset {
1180 item_ix: cursor.start().0,
1181 offset_in_item: rendered_height - available_height,
1182 };
1183 self.set_scroll_anchor(None);
1184 }
1185 };
1186 }
1187 }
1188
1189 if let Some(anchor) = self.scroll_anchor.as_mut() {
1190 anchor.provisional = preserve_anchor && provisional;
1191 anchor.pending_end = !preserve_anchor && provisional;
1192 }
1193
1194 if !provisional {
1196 let mut leading_overdraw = scroll_top.offset_in_item;
1197 while leading_overdraw < self.overdraw {
1198 cursor.prev();
1199 if let Some(item) = cursor.item() {
1200 let size = if let ListItem::Measured { size, .. } = item {
1201 *size
1202 } else {
1203 let mut element = render_item(cursor.start().0, window, cx);
1204 element.layout_as_root(available_item_space, window, cx)
1205 };
1206
1207 leading_overdraw += size.height;
1208 let ready = self.is_item_ready(cursor.start().0, cx);
1209 measured_items.push_front(item.with_measurement(size, ready));
1210 if !ready {
1211 break;
1212 }
1213 } else {
1214 break;
1215 }
1216 }
1217 }
1218
1219 let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
1220 let mut cursor = old_items.cursor::<Count>(());
1221 let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right);
1222 new_items.extend(measured_items, ());
1223 cursor.seek(&Count(measured_range.end), Bias::Right);
1224 new_items.append(cursor.suffix(), ());
1225 self.items = new_items;
1226
1227 if !provisional && self.follow_state.has_stopped_following() {
1231 let padding = self.last_padding.unwrap_or_default();
1232 let total_height = self.items.summary().height + padding.top + padding.bottom;
1233 let scroll_offset = self.scroll_top(&scroll_top);
1234 if scroll_offset + available_height >= total_height - px(1.0) {
1235 self.follow_state.start_following();
1236 }
1237 }
1238
1239 if !rendered_focused_item {
1243 let mut cursor = self
1244 .items
1245 .filter::<_, Count>((), |summary| summary.has_focus_handles);
1246 cursor.next();
1247 while let Some(item) = cursor.item() {
1248 if item.contains_focused(window, cx) {
1249 let item_index = cursor.start().0;
1250 let mut element = render_item(cursor.start().0, window, cx);
1251 let size = element.layout_as_root(available_item_space, window, cx);
1252 item_layouts.push_back(ItemLayout {
1253 index: item_index,
1254 element,
1255 size,
1256 });
1257 break;
1258 }
1259 cursor.next();
1260 }
1261 }
1262
1263 LayoutItemsResponse {
1264 max_item_width,
1265 scroll_top,
1266 item_layouts,
1267 }
1268 }
1269
1270 fn prepaint_items(
1271 &mut self,
1272 bounds: Bounds<Pixels>,
1273 padding: Edges<Pixels>,
1274 autoscroll: bool,
1275 render_item: &mut RenderItemFn,
1276 window: &mut Window,
1277 cx: &mut App,
1278 ) -> Result<LayoutItemsResponse, ListOffset> {
1279 let item_width = bounds.size.width - padding.along(Axis::Horizontal);
1280 window.transact(|window| {
1281 match self.measuring_behavior {
1282 ListMeasuringBehavior::Measure(has_measured) if !has_measured => {
1283 self.layout_all_items(item_width, render_item, window, cx);
1284 }
1285 _ => {}
1286 }
1287
1288 let mut layout_response = self.layout_items(
1289 Some(item_width),
1290 bounds.size.height,
1291 &padding,
1292 render_item,
1293 window,
1294 cx,
1295 );
1296
1297 window.take_autoscroll();
1299
1300 if bounds.size.height > padding.top + padding.bottom {
1302 let mut item_origin = bounds.origin + Point::new(padding.left, padding.top);
1303 item_origin.y -= layout_response.scroll_top.offset_in_item;
1304 for item in &mut layout_response.item_layouts {
1305 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1306 item.element.prepaint_at(item_origin, window, cx);
1307 });
1308
1309 if let Some(autoscroll_bounds) = window.take_autoscroll()
1310 && autoscroll
1311 {
1312 if autoscroll_bounds.top() < bounds.top() {
1313 let mut item_ix = item.index;
1314 let mut offset_in_item = autoscroll_bounds.top() - item_origin.y;
1315
1316 if offset_in_item < Pixels::ZERO {
1321 let mut cursor = self.items.cursor::<Count>(());
1322 cursor.seek(&Count(item_ix), Bias::Right);
1323 while offset_in_item < Pixels::ZERO {
1324 cursor.prev();
1325 let Some(prev_item) = cursor.item() else {
1326 offset_in_item = Pixels::ZERO;
1327 break;
1328 };
1329 let size = prev_item.size().unwrap_or_else(|| {
1330 let mut element = render_item(cursor.start().0, window, cx);
1331 let item_available_size =
1332 size(item_width.into(), AvailableSpace::MinContent);
1333 element.layout_as_root(item_available_size, window, cx)
1334 });
1335 item_ix = cursor.start().0;
1336 offset_in_item += size.height;
1337 }
1338 }
1339
1340 return Err(ListOffset {
1341 item_ix,
1342 offset_in_item,
1343 });
1344 } else if autoscroll_bounds.bottom() > bounds.bottom() {
1345 let mut cursor = self.items.cursor::<Count>(());
1346 cursor.seek(&Count(item.index), Bias::Right);
1347 let mut height = bounds.size.height - padding.top - padding.bottom;
1348
1349 height -= autoscroll_bounds.bottom() - item_origin.y;
1351
1352 while height > Pixels::ZERO {
1354 cursor.prev();
1355 let Some(item) = cursor.item() else { break };
1356
1357 let size = item.size().unwrap_or_else(|| {
1358 let mut item = render_item(cursor.start().0, window, cx);
1359 let item_available_size =
1360 size(item_width.into(), AvailableSpace::MinContent);
1361 item.layout_as_root(item_available_size, window, cx)
1362 });
1363 height -= size.height;
1364 }
1365
1366 return Err(ListOffset {
1367 item_ix: cursor.start().0,
1368 offset_in_item: if height < Pixels::ZERO {
1369 -height
1370 } else {
1371 Pixels::ZERO
1372 },
1373 });
1374 }
1375 }
1376
1377 item_origin.y += item.size.height;
1378 }
1379 } else {
1380 layout_response.item_layouts.clear();
1381 }
1382
1383 Ok(layout_response)
1384 })
1385 }
1386
1387 fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
1390 let Some(bounds) = self.last_layout_bounds else {
1391 return;
1392 };
1393 let height = bounds.size.height;
1394
1395 let padding = self.last_padding.unwrap_or_default();
1396 let content_height = self
1399 .scrollbar_drag_start_height
1400 .unwrap_or_else(|| self.items.summary().height);
1401 let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
1402 let new_scroll_top = (-point.y).max(px(0.)).min(scroll_max);
1403
1404 let dragged_to_end =
1407 scroll_max > px(0.) && new_scroll_top >= (scroll_max - px(1.0)).max(px(0.));
1408 if dragged_to_end && matches!(self.follow_state, FollowState::Tail { .. }) {
1409 self.follow_state = FollowState::Tail { is_following: true };
1410 let item_count = self.items.summary().count;
1411 self.set_scroll_anchor(Some(ListOffset {
1412 item_ix: item_count,
1413 offset_in_item: px(0.),
1414 }));
1415 return;
1416 }
1417
1418 self.follow_state.stop_following();
1419
1420 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
1421 self.set_scroll_anchor(None);
1422 } else {
1423 let (start, _, _) =
1424 self.items
1425 .find::<ListItemSummary, _>((), &Height(new_scroll_top), Bias::Right);
1426
1427 let scroll_top = ListOffset {
1428 item_ix: start.count,
1429 offset_in_item: new_scroll_top - start.height,
1430 };
1431 self.set_scroll_anchor(Some(scroll_top));
1432 }
1433 }
1434}
1435
1436impl std::fmt::Debug for ListItem {
1437 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1438 match self {
1439 Self::Unmeasured { .. } => write!(f, "Unrendered"),
1440 Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
1441 }
1442 }
1443}
1444
1445#[derive(Debug, Clone, Copy, Default, PartialEq)]
1448pub struct ListOffset {
1449 pub item_ix: usize,
1451 pub offset_in_item: Pixels,
1453}
1454
1455impl Element for List {
1456 type RequestLayoutState = ();
1457 type PrepaintState = ListPrepaintState;
1458
1459 fn id(&self) -> Option<crate::ElementId> {
1460 None
1461 }
1462
1463 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1464 None
1465 }
1466
1467 fn request_layout(
1468 &mut self,
1469 _id: Option<&GlobalElementId>,
1470 _inspector_id: Option<&InspectorElementId>,
1471 window: &mut Window,
1472 cx: &mut App,
1473 ) -> (crate::LayoutId, Self::RequestLayoutState) {
1474 let layout_id = match self.sizing_behavior {
1475 ListSizingBehavior::Infer => {
1476 let mut style = Style::default();
1477 style.overflow.y = Overflow::Scroll;
1478 style.refine(&self.style);
1479 window.with_text_style(style.text_style().cloned(), |window| {
1480 let state = &mut *self.state.0.borrow_mut();
1481
1482 let available_height = if let Some(last_bounds) = state.last_layout_bounds {
1483 last_bounds.size.height
1484 } else {
1485 state.overdraw
1488 };
1489 let padding = content_insets(
1490 &style,
1491 state.last_layout_bounds.unwrap_or_default().size,
1492 window.rem_size(),
1493 );
1494
1495 let layout_response = state.layout_items(
1496 None,
1497 available_height,
1498 &padding,
1499 &mut self.render_item,
1500 window,
1501 cx,
1502 );
1503 let max_element_width = layout_response.max_item_width;
1504
1505 let summary = state.items.summary();
1506 let total_height = summary.height;
1507
1508 window.request_keyed_measured_layout(
1509 style,
1510 (max_element_width, total_height),
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 { 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}