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_measured_layout(
1509 style,
1510 move |known_dimensions, available_space, _window, _cx| {
1511 let width =
1512 known_dimensions
1513 .width
1514 .unwrap_or(match available_space.width {
1515 AvailableSpace::Definite(x) => x,
1516 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1517 max_element_width
1518 }
1519 });
1520 let height = match available_space.height {
1521 AvailableSpace::Definite(height) => total_height.min(height),
1522 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1523 total_height
1524 }
1525 };
1526 size(width, height)
1527 },
1528 )
1529 })
1530 }
1531 ListSizingBehavior::Auto => {
1532 let mut style = Style::default();
1533 style.refine(&self.style);
1534 window.with_text_style(style.text_style().cloned(), |window| {
1535 window.request_layout(style, None, cx)
1536 })
1537 }
1538 };
1539 (layout_id, ())
1540 }
1541
1542 fn prepaint(
1543 &mut self,
1544 _id: Option<&GlobalElementId>,
1545 _inspector_id: Option<&InspectorElementId>,
1546 bounds: Bounds<Pixels>,
1547 _: &mut Self::RequestLayoutState,
1548 window: &mut Window,
1549 cx: &mut App,
1550 ) -> ListPrepaintState {
1551 let state = &mut *self.state.0.borrow_mut();
1552 state.reset = false;
1553
1554 let mut style = Style::default();
1555 style.refine(&self.style);
1556
1557 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1558
1559 let padding = content_insets(&style, bounds.size, window.rem_size());
1560
1561 let last_item_width =
1564 state
1565 .last_layout_bounds
1566 .zip(state.last_padding)
1567 .map(|(last_bounds, last_padding)| {
1568 last_bounds.size.width - last_padding.along(Axis::Horizontal)
1569 });
1570 if last_item_width
1571 .is_none_or(|width| width != bounds.size.width - padding.along(Axis::Horizontal))
1572 {
1573 let new_items = SumTree::from_iter(
1574 state.items.iter().map(|item| ListItem::Unmeasured {
1575 size_hint: None,
1576 focus_handle: item.focus_handle(),
1577 }),
1578 (),
1579 );
1580
1581 state.items = new_items;
1582 state.measuring_behavior.reset();
1583 }
1584
1585 let mut autoscroll = true;
1586 let layout = loop {
1587 match state.prepaint_items(
1588 bounds,
1589 padding,
1590 autoscroll,
1591 &mut self.render_item,
1592 window,
1593 cx,
1594 ) {
1595 Ok(layout) => break layout,
1596 Err(autoscroll_request) => {
1597 state.set_scroll_anchor(Some(autoscroll_request));
1598 autoscroll = false;
1599 }
1600 }
1601 };
1602
1603 state.last_layout_bounds = Some(bounds);
1604 state.last_padding = Some(padding);
1605 ListPrepaintState { hitbox, layout }
1606 }
1607
1608 fn paint(
1609 &mut self,
1610 _id: Option<&GlobalElementId>,
1611 _inspector_id: Option<&InspectorElementId>,
1612 bounds: Bounds<crate::Pixels>,
1613 _: &mut Self::RequestLayoutState,
1614 prepaint: &mut Self::PrepaintState,
1615 window: &mut Window,
1616 cx: &mut App,
1617 ) {
1618 let current_view = window.current_view();
1619
1620 let list_state = self.state.clone();
1626 let height = bounds.size.height;
1627 let scroll_top = prepaint.layout.scroll_top;
1628 let hitbox_id = prepaint.hitbox.id;
1629 let mut accumulated_scroll_delta = ScrollDelta::default();
1630 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
1631 if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
1632 accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
1633 let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1634 list_state.0.borrow_mut().scroll(
1635 &scroll_top,
1636 height,
1637 pixel_delta,
1638 current_view,
1639 window,
1640 cx,
1641 )
1642 }
1643 });
1644
1645 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1646 for item in &mut prepaint.layout.item_layouts {
1647 item.element.paint(window, cx);
1648 }
1649 });
1650 }
1651}
1652
1653fn content_insets(style: &Style, size: Size<Pixels>, rem_size: Pixels) -> Edges<Pixels> {
1654 let padding = style.padding.to_pixels(size.into(), rem_size);
1655 let border = style.border_widths.to_pixels(rem_size);
1656
1657 padding + border
1658}
1659
1660impl Styled for List {
1661 fn style(&mut self) -> &mut StyleRefinement {
1662 &mut self.style
1663 }
1664}
1665
1666impl sum_tree::Item for ListItem {
1667 type Summary = ListItemSummary;
1668
1669 fn summary(&self, _: ()) -> Self::Summary {
1670 match self {
1671 ListItem::Unmeasured {
1672 size_hint,
1673 focus_handle,
1674 } => ListItemSummary {
1675 count: 1,
1676 rendered_count: 0,
1677 unrendered_count: 1,
1678 height: if let Some(size) = size_hint {
1679 size.height
1680 } else {
1681 px(0.)
1682 },
1683 has_focus_handles: focus_handle.is_some(),
1684 has_unknown_height: size_hint.is_none(),
1685 },
1686 ListItem::Measured {
1687 size, focus_handle, ..
1688 } => ListItemSummary {
1689 count: 1,
1690 rendered_count: 1,
1691 unrendered_count: 0,
1692 height: size.height,
1693 has_focus_handles: focus_handle.is_some(),
1694 has_unknown_height: false,
1695 },
1696 }
1697 }
1698}
1699
1700impl sum_tree::ContextLessSummary for ListItemSummary {
1701 fn zero() -> Self {
1702 Default::default()
1703 }
1704
1705 fn add_summary(&mut self, summary: &Self) {
1706 self.count += summary.count;
1707 self.rendered_count += summary.rendered_count;
1708 self.unrendered_count += summary.unrendered_count;
1709 self.height += summary.height;
1710 self.has_focus_handles |= summary.has_focus_handles;
1711 self.has_unknown_height |= summary.has_unknown_height;
1712 }
1713}
1714
1715impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1716 fn zero(_cx: ()) -> Self {
1717 Default::default()
1718 }
1719
1720 fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1721 self.0 += summary.count;
1722 }
1723}
1724
1725impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1726 fn zero(_cx: ()) -> Self {
1727 Default::default()
1728 }
1729
1730 fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1731 self.0 += summary.height;
1732 }
1733}
1734
1735impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1736 fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1737 Ord::cmp(&self.0, &other.count)
1738 }
1739}
1740
1741impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1742 fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1743 Ord::cmp(&self.0, &other.height)
1744 }
1745}
1746
1747#[cfg(test)]
1748mod test {
1749
1750 use gpui::{ScrollDelta, ScrollEvent};
1751 use std::cell::{Cell, RefCell};
1752 use std::rc::Rc;
1753
1754 use crate::{
1755 self as gpui, AnyElement, AppContext, Bounds, Context, Element, FollowMode,
1756 InteractiveElement, IntoElement, ListOffset, ListSizingBehavior, ListState, ParentElement,
1757 Pixels, Render, Styled, TestAppContext, VisualTestContext, Window, canvas, div, list,
1758 point, px, size,
1759 };
1760
1761 #[gpui::test]
1762 fn test_autoscroll_above_item_top_renders_items_above(cx: &mut TestAppContext) {
1763 let cx = cx.add_empty_window();
1764
1765 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1766 state.scroll_to(gpui::ListOffset {
1767 item_ix: 2,
1768 offset_in_item: px(0.),
1769 });
1770
1771 struct TestView(ListState);
1772 impl Render for TestView {
1773 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1774 list(self.0.clone(), |ix, _, _| {
1775 if ix == 2 {
1776 canvas(
1779 |bounds, window, _| {
1780 window.request_autoscroll(Bounds::from_corners(
1781 point(bounds.left(), bounds.top() - px(30.)),
1782 point(bounds.right(), bounds.top() + px(5.)),
1783 ));
1784 },
1785 |_, _, _, _| {},
1786 )
1787 .h(px(20.))
1788 .w_full()
1789 .into_any()
1790 } else {
1791 div().h(px(20.)).w_full().into_any()
1792 }
1793 })
1794 .w_full()
1795 .h_full()
1796 }
1797 }
1798
1799 cx.draw(point(px(0.), px(0.)), size(px(100.), px(60.)), |_, cx| {
1800 cx.new(|_| TestView(state.clone())).into_any_element()
1801 });
1802
1803 let scroll_top = state.logical_scroll_top();
1805 assert!(
1806 scroll_top.offset_in_item >= px(0.),
1807 "offset_in_item must never be negative (would leave blank space above), got {:?}",
1808 scroll_top.offset_in_item,
1809 );
1810 assert_eq!(scroll_top.item_ix, 0);
1811 assert_eq!(scroll_top.offset_in_item, px(10.));
1812 }
1813
1814 #[gpui::test]
1815 fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
1816 let cx = cx.add_empty_window();
1817
1818 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1819
1820 state.scroll_to(gpui::ListOffset {
1822 item_ix: 0,
1823 offset_in_item: px(0.0),
1824 });
1825
1826 struct TestView(ListState);
1827 impl Render for TestView {
1828 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1829 list(self.0.clone(), |_, _, _| {
1830 div().h(px(10.)).w_full().into_any()
1831 })
1832 .w_full()
1833 .h_full()
1834 }
1835 }
1836
1837 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1839 cx.new(|_| TestView(state.clone())).into_any_element()
1840 });
1841
1842 state.reset(5);
1844
1845 cx.simulate_event(ScrollEvent {
1847 position: point(px(1.), px(1.)),
1848 delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
1849 ..Default::default()
1850 });
1851
1852 assert_eq!(state.logical_scroll_top().item_ix, 0);
1854 assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
1855 }
1856
1857 #[gpui::test]
1858 fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
1859 let cx = cx.add_empty_window();
1860
1861 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1862
1863 struct TestView(ListState);
1864 impl Render for TestView {
1865 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1866 list(self.0.clone(), |_, _, _| {
1867 div().h(px(20.)).w_full().into_any()
1868 })
1869 .w_full()
1870 .h_full()
1871 }
1872 }
1873
1874 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1876 cx.new(|_| TestView(state.clone())).into_any_element()
1877 });
1878
1879 state.scroll_by(px(30.));
1881
1882 let offset = state.logical_scroll_top();
1884 assert_eq!(offset.item_ix, 1);
1885 assert_eq!(offset.offset_in_item, px(10.));
1886
1887 state.scroll_by(px(-30.));
1889
1890 let offset = state.logical_scroll_top();
1892 assert_eq!(offset.item_ix, 0);
1893 assert_eq!(offset.offset_in_item, px(0.));
1894
1895 state.scroll_by(px(0.));
1897 let offset = state.logical_scroll_top();
1898 assert_eq!(offset.item_ix, 0);
1899 assert_eq!(offset.offset_in_item, px(0.));
1900 }
1901
1902 #[gpui::test]
1903 fn test_child_scroll_handler_can_stop_list_scroll(cx: &mut TestAppContext) {
1904 let cx = cx.add_empty_window();
1905
1906 let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1907 let child_saw_event = Rc::new(Cell::new(false));
1908
1909 struct TestView {
1910 state: ListState,
1911 child_saw_event: Rc<Cell<bool>>,
1912 }
1913 impl Render for TestView {
1914 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1915 let child_saw_event = self.child_saw_event.clone();
1916 list(self.state.clone(), move |_, _, _| {
1917 let child_saw_event = child_saw_event.clone();
1918 div()
1919 .h(px(20.))
1920 .w_full()
1921 .on_scroll(move |_, _, cx| {
1922 child_saw_event.set(true);
1923 cx.stop_propagation();
1924 })
1925 .into_any()
1926 })
1927 .w_full()
1928 .h_full()
1929 }
1930 }
1931
1932 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1933 cx.new(|_| TestView {
1934 state: state.clone(),
1935 child_saw_event: child_saw_event.clone(),
1936 })
1937 .into_any_element()
1938 });
1939
1940 cx.simulate_event(ScrollEvent {
1941 position: point(px(50.), px(10.)),
1942 delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
1943 ..Default::default()
1944 });
1945
1946 assert!(
1947 child_saw_event.get(),
1948 "the child's scroll-wheel handler should run"
1949 );
1950 let offset = state.logical_scroll_top();
1952 assert_eq!(offset.item_ix, 0);
1953 assert_eq!(offset.offset_in_item, px(0.));
1954 }
1955
1956 #[gpui::test]
1957 fn test_item_viewport_queries_return_none_before_layout(_cx: &mut TestAppContext) {
1958 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
1959
1960 assert_eq!(state.item_is_above_viewport(0), None);
1961 assert_eq!(state.item_is_below_viewport(0), None);
1962 }
1963
1964 #[gpui::test]
1965 fn test_item_viewport_queries_before_logical_scroll_top(cx: &mut TestAppContext) {
1966 let cx = cx.add_empty_window();
1967
1968 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
1969
1970 state.scroll_to(gpui::ListOffset {
1971 item_ix: 2,
1972 offset_in_item: px(0.),
1973 });
1974 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1975 cx.new(|_| TestListView(state.clone())).into_any_element()
1976 });
1977
1978 assert_eq!(state.item_is_above_viewport(1), Some(true));
1979 assert_eq!(state.item_is_below_viewport(1), Some(false));
1980 }
1981
1982 #[gpui::test]
1983 fn test_item_viewport_queries_measured_item_inside_viewport(cx: &mut TestAppContext) {
1984 let cx = cx.add_empty_window();
1985
1986 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
1987
1988 state.scroll_to(gpui::ListOffset {
1989 item_ix: 2,
1990 offset_in_item: px(0.),
1991 });
1992 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1993 cx.new(|_| TestListView(state.clone())).into_any_element()
1994 });
1995
1996 assert_eq!(state.item_is_above_viewport(2), Some(false));
1997 assert_eq!(state.item_is_below_viewport(2), Some(false));
1998 }
1999
2000 #[gpui::test]
2001 fn test_item_viewport_queries_measured_item_above_viewport(cx: &mut TestAppContext) {
2002 let cx = cx.add_empty_window();
2003
2004 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2005
2006 state.scroll_to(gpui::ListOffset {
2007 item_ix: 2,
2008 offset_in_item: px(20.),
2009 });
2010 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2011 cx.new(|_| TestListView(state.clone())).into_any_element()
2012 });
2013
2014 assert_eq!(state.item_is_above_viewport(2), Some(true));
2015 assert_eq!(state.item_is_below_viewport(2), Some(false));
2016 }
2017
2018 #[gpui::test]
2019 fn test_item_viewport_queries_measured_item_below_viewport(cx: &mut TestAppContext) {
2020 let cx = cx.add_empty_window();
2021
2022 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2023
2024 state.scroll_to(gpui::ListOffset {
2025 item_ix: 2,
2026 offset_in_item: px(0.),
2027 });
2028 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2029 cx.new(|_| TestListView(state.clone())).into_any_element()
2030 });
2031
2032 assert_eq!(state.item_is_above_viewport(3), Some(false));
2033 assert_eq!(state.item_is_below_viewport(3), Some(true));
2034 }
2035
2036 #[gpui::test]
2037 fn test_item_viewport_queries_remain_stable_with_zero_height_viewport(cx: &mut TestAppContext) {
2038 let cx = cx.add_empty_window();
2039
2040 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2041
2042 state.scroll_to(gpui::ListOffset {
2043 item_ix: 2,
2044 offset_in_item: px(0.),
2045 });
2046 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2047 cx.new(|_| TestListView(state.clone())).into_any_element()
2048 });
2049
2050 assert_eq!(state.item_is_above_viewport(3), Some(false));
2051 assert_eq!(state.item_is_below_viewport(3), Some(true));
2052
2053 cx.draw(point(px(0.), px(0.)), size(px(100.), px(0.)), |_, cx| {
2058 cx.new(|_| TestListView(state.clone())).into_any_element()
2059 });
2060
2061 assert_eq!(state.item_is_above_viewport(1), Some(true));
2062 assert_eq!(state.item_is_below_viewport(1), Some(false));
2063 assert_eq!(state.item_is_above_viewport(3), Some(false));
2064 assert_eq!(state.item_is_below_viewport(3), Some(true));
2065 }
2066
2067 #[gpui::test]
2068 fn test_item_viewport_queries_after_scroll_to_end_before_layout(cx: &mut TestAppContext) {
2069 let cx = cx.add_empty_window();
2070
2071 let state = ListState::new(5, crate::ListAlignment::Top, px(10.)).measure_all();
2072
2073 cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
2074 cx.new(|_| TestListView(state.clone())).into_any_element()
2075 });
2076
2077 state.scroll_to_end();
2078
2079 assert_eq!(state.logical_scroll_top().item_ix, state.item_count());
2080 assert_eq!(state.item_is_above_viewport(0), Some(true));
2081 assert_eq!(state.item_is_below_viewport(0), Some(false));
2082 }
2083
2084 #[gpui::test]
2085 fn test_measure_all_after_width_change(cx: &mut TestAppContext) {
2086 let cx = cx.add_empty_window();
2087
2088 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
2089
2090 struct TestView(ListState);
2091 impl Render for TestView {
2092 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2093 list(self.0.clone(), |_, _, _| {
2094 div().h(px(50.)).w_full().into_any()
2095 })
2096 .w_full()
2097 .h_full()
2098 }
2099 }
2100
2101 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
2102
2103 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2106 view.clone().into_any_element()
2107 });
2108 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2109
2110 cx.draw(point(px(0.), px(0.)), size(px(200.), px(200.)), |_, _| {
2114 view.into_any_element()
2115 });
2116 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
2117 }
2118
2119 #[gpui::test]
2120 fn test_remeasure(cx: &mut TestAppContext) {
2121 let cx = cx.add_empty_window();
2122
2123 let item_height = Rc::new(Cell::new(100usize));
2127 let state = ListState::new(10, crate::ListAlignment::Top, px(10.));
2128
2129 struct TestView {
2130 state: ListState,
2131 item_height: Rc<Cell<usize>>,
2132 }
2133
2134 impl Render for TestView {
2135 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2136 let height = self.item_height.get();
2137 list(self.state.clone(), move |_, _, _| {
2138 div().h(px(height as f32)).w_full().into_any()
2139 })
2140 .w_full()
2141 .h_full()
2142 }
2143 }
2144
2145 let state_clone = state.clone();
2146 let item_height_clone = item_height.clone();
2147 let view = cx.update(|_, cx| {
2148 cx.new(|_| TestView {
2149 state: state_clone,
2150 item_height: item_height_clone,
2151 })
2152 });
2153
2154 state.scroll_to(gpui::ListOffset {
2157 item_ix: 2,
2158 offset_in_item: px(40.),
2159 });
2160
2161 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2162 view.clone().into_any_element()
2163 });
2164
2165 let offset = state.logical_scroll_top();
2166 assert_eq!(offset.item_ix, 2);
2167 assert_eq!(offset.offset_in_item, px(40.));
2168
2169 item_height.set(50);
2174 state.remeasure();
2175
2176 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2177 view.into_any_element()
2178 });
2179
2180 let offset = state.logical_scroll_top();
2181 assert_eq!(offset.item_ix, 2);
2182 assert_eq!(offset.offset_in_item, px(20.));
2183 }
2184
2185 #[gpui::test]
2186 fn test_remeasure_item_preserves_scroll_offset(cx: &mut TestAppContext) {
2187 let cx = cx.add_empty_window();
2188
2189 let item_height = Rc::new(Cell::new(100usize));
2190 let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2191
2192 struct TestView {
2193 state: ListState,
2194 item_height: Rc<Cell<usize>>,
2195 }
2196
2197 impl Render for TestView {
2198 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2199 let height = self.item_height.get();
2200 list(self.state.clone(), move |index, _, _| {
2201 let height = if index == 5 { height } else { 100 };
2202 div().h(px(height as f32)).w_full().into_any()
2203 })
2204 .w_full()
2205 .h_full()
2206 }
2207 }
2208
2209 let state_clone = state.clone();
2210 let item_height_clone = item_height.clone();
2211 let view = cx.update(|_, cx| {
2212 cx.new(|_| TestView {
2213 state: state_clone,
2214 item_height: item_height_clone,
2215 })
2216 });
2217
2218 state.scroll_to(gpui::ListOffset {
2219 item_ix: 5,
2220 offset_in_item: px(40.),
2221 });
2222
2223 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2224 view.clone().into_any_element()
2225 });
2226
2227 item_height.set(200);
2228 state.remeasure_items(5..6);
2229
2230 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2231 view.into_any_element()
2232 });
2233
2234 let offset = state.logical_scroll_top();
2235 assert_eq!(offset.item_ix, 5);
2236 assert_eq!(offset.offset_in_item, px(40.));
2237 }
2238
2239 #[gpui::test]
2240 fn test_provisional_item_heights_keep_scroll_anchor(cx: &mut TestAppContext) {
2241 let cx = cx.add_empty_window();
2242 let state = ListState::new(20, crate::ListAlignment::Top, px(100.));
2243 let painted = Rc::new(RefCell::new(Vec::new()));
2244 let first_rendered = Rc::new(Cell::new(None::<usize>));
2245 let ready = item_readiness(&state, false);
2246 state.set_follow_mode(FollowMode::Tail);
2247 state.scroll_to(list_offset(10, 40.));
2248
2249 for (height, measurement_ready) in [(0., false), (100., false), (100., true)] {
2250 ready.set(measurement_ready);
2251 painted.borrow_mut().clear();
2252 first_rendered.set(None);
2253 draw_list(
2254 &state,
2255 200.,
2256 {
2257 let painted = painted.clone();
2258 let first_rendered = first_rendered.clone();
2259 move |index| {
2260 first_rendered.set(Some(first_rendered.get().unwrap_or(index).min(index)));
2261 painted_item(index, height, &painted)
2262 }
2263 },
2264 cx,
2265 );
2266 assert_eq!(state.logical_scroll_top(), list_offset(10, 40.));
2267 assert!(!state.is_following_tail());
2268 assert_eq!(
2269 first_rendered.get(),
2270 Some(if measurement_ready { 9 } else { 10 })
2271 );
2272 if height > 0. {
2273 assert_eq!(
2274 painted.borrow().as_slice(),
2275 &[
2276 (10, px(-40.), px(60.)),
2277 (11, px(60.), px(160.)),
2278 (12, px(160.), px(260.)),
2279 ]
2280 );
2281 }
2282 }
2283 }
2284
2285 #[gpui::test]
2286 fn test_unready_measurements_preserve_pending_fraction(cx: &mut TestAppContext) {
2287 let cx = cx.add_empty_window();
2288 for (provisional_height, destination, final_height, expected_offset) in [
2289 (Some(200.), None, 200., 100.),
2290 (None, Some(40.), 200., 80.),
2291 (Some(200.), Some(50.), 200., 50.),
2292 (Some(0.), Some(40.), 20., 20.),
2293 (Some(10.), Some(40.), 100., 40.),
2294 (Some(200.), Some(50.), 300., 50.),
2295 ] {
2296 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2297 let painted = Rc::new(RefCell::new(Vec::new()));
2298 let draw = |height, cx: &mut VisualTestContext| {
2299 painted.borrow_mut().clear();
2300 let painted = painted.clone();
2301 draw_list(
2302 &state,
2303 200.,
2304 move |index| {
2305 painted_item(index, if index == 5 { height } else { 100. }, &painted)
2306 },
2307 cx,
2308 );
2309 };
2310 let ready = item_readiness(&state, true);
2311 state.scroll_to(list_offset(5, 50.));
2312 draw(100., cx);
2313 ready.set(false);
2314 state.remeasure();
2315 if let Some(height) = provisional_height {
2316 for height in [0., height, height] {
2317 draw(height, cx);
2318 assert_eq!(state.logical_scroll_top(), list_offset(5, 50.));
2319 }
2320 }
2321 if let Some(offset) = destination {
2322 state.scroll_to(list_offset(5, offset));
2323 }
2324 ready.set(true);
2325 for _ in 0..2 {
2326 draw(final_height, cx);
2327 assert_eq!(state.logical_scroll_top(), list_offset(5, expected_offset));
2328 assert_eq!(
2329 painted.borrow().first().copied(),
2330 Some((5, px(-expected_offset), px(final_height - expected_offset)))
2331 );
2332 }
2333 }
2334 }
2335
2336 #[gpui::test]
2337 fn test_navigation_cancels_provisional_and_paints_destination(cx: &mut TestAppContext) {
2338 let cx = cx.add_empty_window();
2339 for measured in [false, true] {
2340 let navigations: [(&str, fn(&ListState), usize, f32); 7] = [
2341 (
2342 "scroll_to",
2343 |state| state.scroll_to(list_offset(12, 0.)),
2344 12,
2345 0.,
2346 ),
2347 ("end", ListState::scroll_to_end, 19, 150.),
2348 ("down", |state| state.scroll_by(px(5000.)), 19, 150.),
2349 (
2350 "up",
2351 |state| state.scroll_by(px(-5000.)),
2352 if measured { 0 } else { 6 },
2353 0.,
2354 ),
2355 (
2356 "reveal_below",
2357 |state| state.scroll_to_reveal_item(10),
2358 10,
2359 150.,
2360 ),
2361 (
2362 "reveal_above",
2363 |state| state.scroll_to_reveal_item(0),
2364 0,
2365 0.,
2366 ),
2367 (
2368 "follow_tail",
2369 |state| state.set_follow_mode(FollowMode::Tail),
2370 19,
2371 150.,
2372 ),
2373 ];
2374 for (name, navigate, destination, top) in navigations {
2375 let state = ListState::new(20, crate::ListAlignment::Top, px(0.));
2376 let state = if measured { state.measure_all() } else { state };
2377 let painted = Rc::new(RefCell::new(Vec::new()));
2378 let draw = |cx: &mut VisualTestContext| {
2379 painted.borrow_mut().clear();
2380 let painted = painted.clone();
2381 draw_list(
2382 &state,
2383 200.,
2384 move |index| {
2385 painted_item(index, if index == 5 { 0. } else { 50. }, &painted)
2386 },
2387 cx,
2388 );
2389 };
2390 state.set_item_measurement_readiness(|index, _| index != 5);
2391 state.scroll_to(list_offset(5, 20.));
2392 state.remeasure_items(5..6);
2393 draw(cx);
2394 assert!(state.0.borrow().is_provisional(), "{name}");
2395 navigate(&state);
2396 assert!(!state.0.borrow().is_provisional(), "{name}");
2397 draw(cx);
2398 assert!(!state.0.borrow().is_provisional(), "{name}");
2399 assert_eq!(
2400 painted
2401 .borrow()
2402 .iter()
2403 .find(|(index, _, _)| *index == destination)
2404 .copied(),
2405 Some((destination, px(top), px(top + 50.))),
2406 "{name}, measured={measured}",
2407 );
2408 }
2409 }
2410
2411 let navigations: [(&str, fn(&ListState)); 6] = [
2412 ("end_sentinel", |state| state.scroll_to(list_offset(3, 0.))),
2413 ("scroll_to_end", ListState::scroll_to_end),
2414 ("follow_tail", |state| {
2415 state.set_follow_mode(FollowMode::Tail)
2416 }),
2417 ("horizontal", ListState::scroll_to_end),
2418 ("pause_tail", |state| {
2419 state.set_follow_mode(FollowMode::Tail)
2420 }),
2421 ("disable_tail", |state| {
2422 state.set_follow_mode(FollowMode::Tail)
2423 }),
2424 ];
2425 for (name, navigate) in navigations {
2426 let state = ListState::new(3, crate::ListAlignment::Top, px(0.)).measure_all();
2427 let ready = item_readiness(&state, false);
2428 let painted = Rc::new(RefCell::new(Vec::new()));
2429 let draw = |height, cx: &mut VisualTestContext| {
2430 painted.borrow_mut().clear();
2431 let painted = painted.clone();
2432 draw_list(
2433 &state,
2434 200.,
2435 move |index| painted_item(index, height, &painted),
2436 cx,
2437 );
2438 };
2439 navigate(&state);
2440 for (height, measurement_ready, expected) in [
2441 (
2442 100.,
2443 false,
2444 [(1, px(0.), px(100.)), (2, px(100.), px(200.))],
2445 ),
2446 (
2447 150.,
2448 true,
2449 [(1, px(-100.), px(50.)), (2, px(50.), px(200.))],
2450 ),
2451 ] {
2452 if measurement_ready {
2453 match name {
2454 "horizontal" => cx.simulate_event(ScrollEvent {
2455 position: point(px(50.), px(100.)),
2456 delta: ScrollDelta::Pixels(point(px(20.), px(0.))),
2457 ..ScrollEvent::default()
2458 }),
2459 "pause_tail" => state.pause_following_tail(),
2460 "disable_tail" => state.set_follow_mode(FollowMode::Normal),
2461 _ => {}
2462 }
2463 }
2464 ready.set(measurement_ready);
2465 draw(height, cx);
2466 if !measurement_ready {
2467 assert_eq!(
2468 state.scroll_px_offset_for_scrollbar().y,
2469 px(-100.),
2470 "{name}"
2471 );
2472 assert_eq!(state.logical_scroll_top(), list_offset(1, 0.), "{name}");
2473 assert_eq!(state.item_is_above_viewport(2), None, "{name}");
2474 }
2475 let paused = name == "pause_tail" || name == "disable_tail";
2476 let expected = if measurement_ready && paused {
2477 [(1, px(0.), px(150.)), (2, px(150.), px(300.))]
2478 } else {
2479 expected
2480 };
2481 assert_eq!(
2482 state.is_following_tail(),
2483 name == "follow_tail" || (paused && !measurement_ready),
2484 "{name}"
2485 );
2486 assert_eq!(painted.borrow().as_slice(), &expected, "{name}");
2487 }
2488 ready.set(false);
2489 navigate(&state);
2490 draw(150., cx);
2491 state.scroll_by(px(-20.));
2492 draw(150., cx);
2493 assert_eq!(state.logical_scroll_top(), list_offset(1, 80.), "{name}");
2494 assert!(!state.is_following_tail(), "{name}");
2495 assert_eq!(
2496 painted.borrow().as_slice(),
2497 &[(1, px(-80.), px(70.)), (2, px(70.), px(220.)),],
2498 "{name}"
2499 );
2500 }
2501 }
2502
2503 #[gpui::test]
2504 fn test_unready_overdraw_and_backfill_preserve_scroll_anchor(cx: &mut TestAppContext) {
2505 let cx = cx.add_empty_window();
2506 for (overdraw, anchor, unready_item) in
2507 [(100., list_offset(0, 0.), 2), (0., list_offset(2, 40.), 1)]
2508 {
2509 let state = ListState::new(3, crate::ListAlignment::Top, px(overdraw));
2510 let ready = Rc::new(Cell::new(false));
2511 state.set_item_measurement_readiness({
2512 let ready = ready.clone();
2513 move |index, _| index != unready_item || ready.get()
2514 });
2515 let painted = Rc::new(RefCell::new(Vec::new()));
2516 let draw = |height, cx: &mut VisualTestContext| {
2517 painted.borrow_mut().clear();
2518 let painted = painted.clone();
2519 draw_list(
2520 &state,
2521 200.,
2522 move |index| {
2523 let height = if index == unready_item { height } else { 100. };
2524 painted_item(index, height, &painted)
2525 },
2526 cx,
2527 );
2528 };
2529 state.set_follow_mode(FollowMode::Tail);
2530 state.scroll_to(anchor);
2531 draw(0., cx);
2532 assert_eq!(state.logical_scroll_top(), anchor);
2533 assert!(!state.is_following_tail());
2534 assert_eq!(
2535 *painted.borrow(),
2536 if unready_item == 2 {
2537 vec![(0, px(0.), px(100.)), (1, px(100.), px(200.))]
2538 } else {
2539 vec![(2, px(-40.), px(60.))]
2540 }
2541 );
2542 ready.set(true);
2543 draw(500., cx);
2544 if unready_item == 2 {
2545 assert_eq!(state.logical_scroll_top(), anchor);
2546 assert!(!state.is_following_tail());
2547 assert_eq!(state.max_offset_for_scrollbar().y, px(500.));
2548 assert_eq!(
2549 painted.borrow().as_slice(),
2550 &[(0, px(0.), px(100.)), (1, px(100.), px(200.))]
2551 );
2552 } else {
2553 assert_eq!(state.logical_scroll_top(), list_offset(1, 400.));
2554 assert!(state.is_following_tail());
2555 assert_eq!(
2556 painted.borrow().as_slice(),
2557 &[(1, px(-400.), px(100.)), (2, px(100.), px(200.))]
2558 );
2559 }
2560 }
2561 }
2562
2563 #[gpui::test]
2564 fn test_unready_overdraw_stops_at_first_pending_item(cx: &mut TestAppContext) {
2565 let cx = cx.add_empty_window();
2566 for anchor in [0, 10] {
2567 let state = ListState::new(13, crate::ListAlignment::Top, px(100.));
2568 let ready = Rc::new(Cell::new(false));
2569 let initially_ready = move |index| {
2570 if anchor == 0 { index < 2 } else { index >= 10 }
2571 };
2572 state.set_item_measurement_readiness({
2573 let ready = ready.clone();
2574 move |index, _| initially_ready(index) || ready.get()
2575 });
2576 state.scroll_to(list_offset(anchor, 0.));
2577 let rendered = Rc::new(RefCell::new(Vec::new()));
2578 let painted = Rc::new(RefCell::new(Vec::new()));
2579 let expected_frames = if anchor == 0 {
2580 [vec![0, 1, 2], vec![0, 1, 2], vec![0, 1, 2], vec![0, 1]]
2581 } else {
2582 [
2583 vec![10, 11, 12, 9],
2584 vec![10, 11, 9],
2585 vec![10, 11, 9],
2586 vec![10, 11],
2587 ]
2588 };
2589 for (frame, expected_rendered) in expected_frames.into_iter().enumerate() {
2590 let measurement_ready = frame >= 2;
2591 ready.set(measurement_ready);
2592 rendered.borrow_mut().clear();
2593 painted.borrow_mut().clear();
2594 draw_list(
2595 &state,
2596 200.,
2597 {
2598 let rendered = rendered.clone();
2599 let painted = painted.clone();
2600 move |index| {
2601 rendered.borrow_mut().push(index);
2602 let height = if initially_ready(index) || measurement_ready {
2603 100.
2604 } else {
2605 0.
2606 };
2607 painted_item(index, height, &painted)
2608 }
2609 },
2610 cx,
2611 );
2612 assert_eq!(*rendered.borrow(), expected_rendered);
2613 assert_eq!(state.item_count(), 13);
2614 assert_eq!(state.logical_scroll_top(), list_offset(anchor, 0.));
2615 assert_eq!(
2616 painted.borrow().as_slice(),
2617 &[(anchor, px(0.), px(100.)), (anchor + 1, px(100.), px(200.))]
2618 );
2619 }
2620 }
2621 }
2622
2623 #[gpui::test]
2624 fn test_scrollbar_and_reset_do_not_resurrect_provisional(cx: &mut TestAppContext) {
2625 let cx = cx.add_empty_window();
2626 let state = ListState::new(20, crate::ListAlignment::Top, px(0.));
2627 let painted = Rc::new(RefCell::new(Vec::new()));
2628 let draw = |cx: &mut VisualTestContext| {
2629 painted.borrow_mut().clear();
2630 let painted = painted.clone();
2631 draw_list(
2632 &state,
2633 200.,
2634 move |index| painted_item(index, if index == 5 { 0. } else { 50. }, &painted),
2635 cx,
2636 );
2637 };
2638 state.set_item_measurement_readiness(|index, _| index != 5);
2639 assert!(!state.0.borrow().is_provisional());
2640 state.set_follow_mode(FollowMode::Tail);
2641 for intervening_frame in [false, true] {
2642 state.scroll_to(list_offset(5, 20.));
2643 state.remeasure_items(5..6);
2644 draw(cx);
2645 state.scrollbar_drag_started();
2646 if intervening_frame {
2647 draw(cx);
2648 assert!(state.0.borrow().is_provisional());
2649 }
2650 state.set_offset_from_scrollbar(point(px(0.), px(-10_000.)));
2651 assert!(!state.0.borrow().is_provisional());
2652 state.scrollbar_drag_ended();
2653 assert!(!state.is_scrollbar_dragging());
2654 draw(cx);
2655 assert_eq!(
2656 painted.borrow().last().copied(),
2657 Some((19, px(150.), px(200.)))
2658 );
2659 assert!(!state.0.borrow().is_provisional());
2660 state.scroll_to(list_offset(5, 20.));
2661 assert!(!state.0.borrow().is_provisional());
2662 draw(cx);
2663 assert!(state.0.borrow().is_provisional());
2664 assert_eq!(state.logical_scroll_top(), list_offset(5, 20.));
2665 }
2666 state.remeasure_items(5..6);
2667 state.reset(20);
2668 assert!(!state.0.borrow().is_provisional());
2669 draw(cx);
2670 assert!(!state.0.borrow().is_provisional());
2671 assert_eq!(state.logical_scroll_top(), ListOffset::default());
2672 assert_eq!(
2673 painted.borrow().first().copied(),
2674 Some((0, px(0.), px(50.)))
2675 );
2676 }
2677
2678 #[gpui::test]
2679 fn test_splice_preserves_only_surviving_scroll_offsets(cx: &mut TestAppContext) {
2680 let cx = cx.add_empty_window();
2681 let painted = Rc::new(RefCell::new(Vec::new()));
2682 let draw = |state: &ListState, height, cx: &mut VisualTestContext| {
2683 painted.borrow_mut().clear();
2684 let painted = painted.clone();
2685 draw_list(
2686 state,
2687 200.,
2688 move |index| painted_item(index, height, &painted),
2689 cx,
2690 );
2691 };
2692 for (provisional, replacement_count) in [(true, 0), (false, 1)] {
2693 let state = ListState::new(20, crate::ListAlignment::Top, px(0.));
2694 let ready = item_readiness(&state, !provisional);
2695 state.scroll_to(list_offset(8, 50.));
2696 state.remeasure_items(8..9);
2697 if provisional {
2698 draw(&state, 100., cx);
2699 }
2700 state.splice(8..9, replacement_count);
2701 assert!(!state.0.borrow().is_provisional());
2702 ready.set(true);
2703 draw(&state, 100., cx);
2704 assert_eq!(state.logical_scroll_top(), list_offset(8, 0.));
2705 assert_eq!(
2706 painted.borrow().first().copied(),
2707 Some((8, px(0.), px(100.)))
2708 );
2709 }
2710 let state = ListState::new(20, crate::ListAlignment::Top, px(0.)).measure_all();
2711 state.scroll_to(list_offset(8, 50.));
2712 draw(&state, 100., cx);
2713 state.remeasure();
2714 state.splice(0..2, 0);
2715 draw(&state, 80., cx);
2716 assert_eq!(state.logical_scroll_top(), list_offset(6, 40.));
2717 assert_eq!(
2718 painted.borrow().first().copied(),
2719 Some((6, px(-40.), px(40.)))
2720 );
2721 let ready = item_readiness(&state, false);
2722 state.remeasure_items(6..7);
2723 state.splice(8..10, 3);
2724 draw(&state, 100., cx);
2725 assert!(state.0.borrow().is_provisional());
2726 assert_eq!(state.logical_scroll_top(), list_offset(6, 40.));
2727 state.splice(0..0, 2);
2728 assert!(!state.0.borrow().is_provisional());
2729 draw(&state, 100., cx);
2730 assert!(state.0.borrow().is_provisional());
2731 assert_eq!(state.logical_scroll_top(), list_offset(8, 40.));
2732 ready.set(true);
2733 draw(&state, 100., cx);
2734 assert_eq!(state.logical_scroll_top(), list_offset(8, 40.));
2735 assert_eq!(
2736 painted.borrow().first().copied(),
2737 Some((8, px(-40.), px(60.)))
2738 );
2739 }
2740
2741 #[gpui::test]
2742 fn test_child_autoscroll_overrides_pending_and_release_fills_viewport(cx: &mut TestAppContext) {
2743 let cx = cx.add_empty_window();
2744 for (count, child, request, expected, released) in [
2745 (10, 2, 40.0..45.0, list_offset(2, 40.), list_offset(2, 40.)),
2746 (3, 2, 40.0..45.0, list_offset(2, 40.), list_offset(1, 0.)),
2747 (10, 4, 80.0..90.0, list_offset(2, 90.), list_offset(2, 90.)),
2748 (10, 2, -130.0..5.0, list_offset(0, 70.), list_offset(0, 70.)),
2749 (10, 2, -250.0..5.0, list_offset(0, 0.), list_offset(0, 0.)),
2750 ] {
2751 let state = ListState::new(count, crate::ListAlignment::Top, px(0.));
2752 let requested = Rc::new(Cell::new(false));
2753 let painted = Rc::new(RefCell::new(Vec::new()));
2754 let draw = |cx: &mut VisualTestContext| {
2755 painted.borrow_mut().clear();
2756 let painted = painted.clone();
2757 let requested = requested.clone();
2758 let request = request.clone();
2759 draw_list(
2760 &state,
2761 200.,
2762 move |index| {
2763 let painted = painted.clone();
2764 let requested = requested.clone();
2765 let request = request.clone();
2766 canvas(
2767 move |bounds, window, _| {
2768 if index == child && !requested.replace(true) {
2769 window.request_autoscroll(Bounds::from_corners(
2770 point(bounds.left(), bounds.top() + px(request.start)),
2771 point(bounds.right(), bounds.top() + px(request.end)),
2772 ));
2773 }
2774 },
2775 move |bounds, _, _, _| {
2776 painted
2777 .borrow_mut()
2778 .push((index, bounds.top(), bounds.bottom()));
2779 },
2780 )
2781 .h(px(100.))
2782 .w_full()
2783 .into_any()
2784 },
2785 cx,
2786 );
2787 };
2788 let ready = item_readiness(&state, false);
2789 state.scroll_to(list_offset(2, 50.));
2790 state.remeasure_items(2..3);
2791 for _ in 0..2 {
2792 draw(cx);
2793 assert!(requested.get());
2794 assert!(state.0.borrow().is_provisional());
2795 assert_eq!(state.logical_scroll_top(), expected);
2796 assert_eq!(
2797 painted.borrow().first().copied(),
2798 Some((
2799 expected.item_ix,
2800 -expected.offset_in_item,
2801 px(100.) - expected.offset_in_item,
2802 ))
2803 );
2804 }
2805 ready.set(true);
2806 draw(cx);
2807 assert!(!state.0.borrow().is_provisional());
2808 assert_eq!(state.logical_scroll_top(), released);
2809 let visible_count = if released.offset_in_item == px(0.) {
2810 2
2811 } else {
2812 3
2813 };
2814 assert_eq!(
2815 painted.borrow().as_slice(),
2816 (0..visible_count)
2817 .map(|index| {
2818 let top = px(index as f32 * 100.) - released.offset_in_item;
2819 (released.item_ix + index, top, top + px(100.))
2820 })
2821 .collect::<Vec<_>>()
2822 .as_slice()
2823 );
2824 }
2825 }
2826
2827 #[gpui::test]
2828 fn test_remeasure_then_scroll_does_not_revert_scroll_position(cx: &mut TestAppContext) {
2829 let cx = cx.add_empty_window();
2830
2831 let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2832
2833 struct TestView(ListState);
2834 impl Render for TestView {
2835 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2836 list(self.0.clone(), |_, _, _| {
2837 div().h(px(100.)).w_full().into_any()
2838 })
2839 .w_full()
2840 .h_full()
2841 }
2842 }
2843
2844 let view = {
2845 let state = state.clone();
2846 cx.update(|_, cx| cx.new(|_| TestView(state)))
2847 };
2848
2849 state.scroll_to(gpui::ListOffset {
2850 item_ix: 5,
2851 offset_in_item: px(40.),
2852 });
2853
2854 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2855 view.clone().into_any_element()
2856 });
2857
2858 state.remeasure_items(5..6);
2859
2860 cx.simulate_event(ScrollEvent {
2861 position: point(px(50.), px(100.)),
2862 delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2863 ..Default::default()
2864 });
2865
2866 let offset = state.logical_scroll_top();
2867 assert_eq!(offset.item_ix, 5);
2868 assert_eq!(offset.offset_in_item, px(70.));
2869
2870 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2871 view.into_any_element()
2872 });
2873
2874 let offset = state.logical_scroll_top();
2875 assert_eq!(offset.item_ix, 5);
2876 assert_eq!(
2877 offset.offset_in_item,
2878 px(70.),
2879 "scrolling after a remeasure should not be reverted by the stale pending scroll"
2880 );
2881 }
2882
2883 #[gpui::test]
2884 fn test_scroll_after_remeasure_clamps_to_shrunk_item_height(cx: &mut TestAppContext) {
2885 let cx = cx.add_empty_window();
2886 for provisional in [false, true] {
2887 let state = ListState::new(20, crate::ListAlignment::Top, px(10.));
2888 let painted = Rc::new(RefCell::new(Vec::new()));
2889 let draw = |height, cx: &mut VisualTestContext| {
2890 painted.borrow_mut().clear();
2891 let painted = painted.clone();
2892 draw_list(
2893 &state,
2894 200.,
2895 move |index| {
2896 painted_item(index, if index == 5 { height } else { 100. }, &painted)
2897 },
2898 cx,
2899 );
2900 };
2901 let ready = item_readiness(&state, true);
2902 state.scroll_to(list_offset(5, 40.));
2903 draw(100., cx);
2904 ready.set(!provisional);
2905 state.remeasure_items(5..6);
2906 if provisional {
2907 draw(100., cx);
2908 }
2909 ready.set(true);
2910 cx.simulate_event(ScrollEvent {
2911 position: point(px(50.), px(100.)),
2912 delta: ScrollDelta::Pixels(point(px(0.), px(-30.))),
2913 ..ScrollEvent::default()
2914 });
2915 assert_eq!(state.logical_scroll_top(), list_offset(5, 70.));
2916 for _ in 0..2 {
2917 draw(50., cx);
2918 assert_eq!(state.logical_scroll_top(), list_offset(5, 50.));
2919 assert_eq!(
2920 painted
2921 .borrow()
2922 .iter()
2923 .find(|(index, _, _)| *index == 6)
2924 .copied(),
2925 Some((6, px(0.), px(100.)))
2926 );
2927 }
2928 }
2929 }
2930
2931 #[gpui::test]
2932 fn test_follow_tail_stays_at_bottom_as_items_grow(cx: &mut TestAppContext) {
2933 let cx = cx.add_empty_window();
2934
2935 let item_height = Rc::new(Cell::new(50usize));
2938 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
2939
2940 struct TestView {
2941 state: ListState,
2942 item_height: Rc<Cell<usize>>,
2943 }
2944 impl Render for TestView {
2945 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2946 let height = self.item_height.get();
2947 list(self.state.clone(), move |_, _, _| {
2948 div().h(px(height as f32)).w_full().into_any()
2949 })
2950 .w_full()
2951 .h_full()
2952 }
2953 }
2954
2955 let state_clone = state.clone();
2956 let item_height_clone = item_height.clone();
2957 let view = cx.update(|_, cx| {
2958 cx.new(|_| TestView {
2959 state: state_clone,
2960 item_height: item_height_clone,
2961 })
2962 });
2963
2964 state.set_follow_mode(FollowMode::Tail);
2965
2966 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2969 view.clone().into_any_element()
2970 });
2971
2972 let offset = state.logical_scroll_top();
2975 assert_eq!(offset.item_ix, 6);
2976 assert_eq!(offset.offset_in_item, px(0.));
2977 assert!(state.is_following_tail());
2978
2979 item_height.set(80);
2982 state.remeasure();
2983
2984 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
2985 view.into_any_element()
2986 });
2987
2988 let offset = state.logical_scroll_top();
2995 assert_eq!(offset.item_ix, 7);
2996 assert_eq!(offset.offset_in_item, px(40.));
2997 assert!(state.is_following_tail());
2998 }
2999
3000 #[gpui::test]
3001 fn test_pause_following_tail_reengages_when_still_at_bottom(cx: &mut TestAppContext) {
3002 let cx = cx.add_empty_window();
3003
3004 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3006
3007 struct TestView(ListState);
3008 impl Render for TestView {
3009 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3010 list(self.0.clone(), |_, _, _| {
3011 div().h(px(50.)).w_full().into_any()
3012 })
3013 .w_full()
3014 .h_full()
3015 }
3016 }
3017
3018 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3019 state.set_follow_mode(FollowMode::Tail);
3020
3021 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3022 view.clone().into_any_element()
3023 });
3024 assert!(state.is_following_tail());
3025
3026 state.pause_following_tail();
3030 assert!(!state.is_following_tail());
3031
3032 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3033 view.into_any_element()
3034 });
3035 assert!(
3036 state.is_following_tail(),
3037 "pausing while at the bottom must re-engage follow-tail on the next layout"
3038 );
3039 }
3040
3041 #[gpui::test]
3042 fn test_pause_following_tail_freezes_off_bottom(cx: &mut TestAppContext) {
3043 let cx = cx.add_empty_window();
3044
3045 let item_height = Rc::new(Cell::new(50usize));
3048 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3049
3050 struct TestView {
3051 state: ListState,
3052 item_height: Rc<Cell<usize>>,
3053 }
3054 impl Render for TestView {
3055 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3056 let height = self.item_height.get();
3057 list(self.state.clone(), move |_, _, _| {
3058 div().h(px(height as f32)).w_full().into_any()
3059 })
3060 .w_full()
3061 .h_full()
3062 }
3063 }
3064
3065 let view = cx.update(|_, cx| {
3066 cx.new(|_| TestView {
3067 state: state.clone(),
3068 item_height: item_height.clone(),
3069 })
3070 });
3071 state.set_follow_mode(FollowMode::Tail);
3072
3073 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3075 view.clone().into_any_element()
3076 });
3077 assert_eq!(state.logical_scroll_top().item_ix, 6);
3078 assert!(state.is_following_tail());
3079
3080 state.pause_following_tail();
3084 item_height.set(80);
3085 state.remeasure();
3086 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3087 view.clone().into_any_element()
3088 });
3089 let offset = state.logical_scroll_top();
3090 assert_eq!(offset.item_ix, 6);
3091 assert_eq!(offset.offset_in_item, px(0.));
3092 assert!(
3093 !state.is_following_tail(),
3094 "a paused list must not re-engage while the frozen top is off the bottom"
3095 );
3096
3097 item_height.set(50);
3100 state.remeasure();
3101 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3102 view.into_any_element()
3103 });
3104 assert!(
3105 state.is_following_tail(),
3106 "returning to the bottom must restore follow-tail"
3107 );
3108 }
3109
3110 #[gpui::test]
3111 fn test_follow_tail_disengages_on_user_scroll(cx: &mut TestAppContext) {
3112 let cx = cx.add_empty_window();
3113
3114 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3116
3117 struct TestView(ListState);
3118 impl Render for TestView {
3119 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3120 list(self.0.clone(), |_, _, _| {
3121 div().h(px(50.)).w_full().into_any()
3122 })
3123 .w_full()
3124 .h_full()
3125 }
3126 }
3127
3128 state.set_follow_mode(FollowMode::Tail);
3129
3130 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, cx| {
3132 cx.new(|_| TestView(state.clone())).into_any_element()
3133 });
3134 assert!(state.is_following_tail());
3135
3136 cx.simulate_event(ScrollEvent {
3139 position: point(px(50.), px(100.)),
3140 delta: ScrollDelta::Pixels(point(px(0.), px(100.))),
3141 ..Default::default()
3142 });
3143
3144 assert!(
3145 !state.is_following_tail(),
3146 "follow-tail should disengage when the user scrolls toward the start"
3147 );
3148 }
3149
3150 #[gpui::test]
3151 fn test_follow_tail_disengages_on_scrollbar_reposition(cx: &mut TestAppContext) {
3152 let cx = cx.add_empty_window();
3153
3154 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3156
3157 struct TestView(ListState);
3158 impl Render for TestView {
3159 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3160 list(self.0.clone(), |_, _, _| {
3161 div().h(px(50.)).w_full().into_any()
3162 })
3163 .w_full()
3164 .h_full()
3165 }
3166 }
3167
3168 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3169
3170 state.set_follow_mode(FollowMode::Tail);
3171
3172 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3174 view.clone().into_any_element()
3175 });
3176 assert!(state.is_following_tail());
3177
3178 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3180
3181 let offset = state.logical_scroll_top();
3182 assert_eq!(offset.item_ix, 3);
3183 assert_eq!(offset.offset_in_item, px(0.));
3184 assert!(
3185 !state.is_following_tail(),
3186 "follow-tail should disengage when the scrollbar manually repositions the list"
3187 );
3188
3189 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3192 view.into_any_element()
3193 });
3194
3195 let offset = state.logical_scroll_top();
3196 assert_eq!(offset.item_ix, 3);
3197 assert_eq!(offset.offset_in_item, px(0.));
3198 }
3199
3200 #[gpui::test]
3201 fn test_scrollbar_drag_with_growing_content(cx: &mut TestAppContext) {
3202 let cx = cx.add_empty_window();
3203
3204 let last_item_height = Rc::new(Cell::new(50usize));
3205 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3206
3207 struct TestView {
3208 state: ListState,
3209 last_item_height: Rc<Cell<usize>>,
3210 }
3211 impl Render for TestView {
3212 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3213 let last_item_height = self.last_item_height.clone();
3214 list(self.state.clone(), move |index, _, _| {
3215 let height = if index == 9 {
3216 last_item_height.get()
3217 } else {
3218 50
3219 };
3220 div().h(px(height as f32)).w_full().into_any()
3221 })
3222 .w_full()
3223 .h_full()
3224 }
3225 }
3226
3227 let view = cx.update(|_, cx| {
3228 cx.new(|_| TestView {
3229 state: state.clone(),
3230 last_item_height: last_item_height.clone(),
3231 })
3232 });
3233
3234 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3235 view.clone().into_any_element()
3236 });
3237
3238 state.scrollbar_drag_started();
3239
3240 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3241 let scrollbar_offset_before_growth = state.scroll_px_offset_for_scrollbar();
3242
3243 let offset = state.logical_scroll_top();
3244 assert_eq!(offset.item_ix, 3);
3245 assert_eq!(offset.offset_in_item, px(0.));
3246
3247 last_item_height.set(550);
3248 state.remeasure_items(9..10);
3249 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3250 view.clone().into_any_element()
3251 });
3252
3253 assert_eq!(state.max_offset_for_scrollbar().y, px(300.));
3254 assert_eq!(
3255 state.scroll_px_offset_for_scrollbar(),
3256 scrollbar_offset_before_growth
3257 );
3258
3259 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3260 let offset = state.logical_scroll_top();
3261 assert_eq!(offset.item_ix, 3);
3262 assert_eq!(offset.offset_in_item, px(0.));
3263 }
3264
3265 #[gpui::test]
3266 fn test_set_follow_tail_snaps_to_bottom(cx: &mut TestAppContext) {
3267 let cx = cx.add_empty_window();
3268
3269 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3271
3272 struct TestView(ListState);
3273 impl Render for TestView {
3274 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3275 list(self.0.clone(), |_, _, _| {
3276 div().h(px(50.)).w_full().into_any()
3277 })
3278 .w_full()
3279 .h_full()
3280 }
3281 }
3282
3283 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3284
3285 state.scroll_to(gpui::ListOffset {
3287 item_ix: 3,
3288 offset_in_item: px(0.),
3289 });
3290
3291 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3292 view.clone().into_any_element()
3293 });
3294
3295 let offset = state.logical_scroll_top();
3296 assert_eq!(offset.item_ix, 3);
3297 assert_eq!(offset.offset_in_item, px(0.));
3298 assert!(!state.is_following_tail());
3299
3300 state.set_follow_mode(FollowMode::Tail);
3303
3304 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3305 view.into_any_element()
3306 });
3307
3308 let offset = state.logical_scroll_top();
3311 assert_eq!(offset.item_ix, 6);
3312 assert_eq!(offset.offset_in_item, px(0.));
3313 assert!(state.is_following_tail());
3314 }
3315
3316 #[gpui::test]
3317 fn test_bottom_aligned_scrollbar_offset_at_end(cx: &mut TestAppContext) {
3318 let cx = cx.add_empty_window();
3319
3320 const ITEMS: usize = 10;
3321 const ITEM_SIZE: f32 = 50.0;
3322
3323 let state = ListState::new(
3324 ITEMS,
3325 crate::ListAlignment::Bottom,
3326 px(ITEMS as f32 * ITEM_SIZE),
3327 );
3328
3329 struct TestView(ListState);
3330 impl Render for TestView {
3331 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3332 list(self.0.clone(), |_, _, _| {
3333 div().h(px(ITEM_SIZE)).w_full().into_any()
3334 })
3335 .w_full()
3336 .h_full()
3337 }
3338 }
3339
3340 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
3341 cx.new(|_| TestView(state.clone())).into_any_element()
3342 });
3343
3344 assert_eq!(state.logical_scroll_top().item_ix, ITEMS);
3347
3348 let max_offset = state.max_offset_for_scrollbar();
3349 let scroll_offset = state.scroll_px_offset_for_scrollbar();
3350
3351 assert_eq!(
3352 -scroll_offset.y, max_offset.y,
3353 "scrollbar offset ({}) should equal max offset ({}) when list is pinned to bottom",
3354 -scroll_offset.y, max_offset.y,
3355 );
3356 }
3357
3358 #[gpui::test]
3362 fn test_follow_tail_reengages_when_scrolled_back_to_bottom(cx: &mut TestAppContext) {
3363 let cx = cx.add_empty_window();
3364
3365 let state = ListState::new(10, crate::ListAlignment::Top, px(0.));
3367
3368 struct TestView(ListState);
3369 impl Render for TestView {
3370 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3371 list(self.0.clone(), |_, _, _| {
3372 div().h(px(50.)).w_full().into_any()
3373 })
3374 .w_full()
3375 .h_full()
3376 }
3377 }
3378
3379 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3380
3381 state.set_follow_mode(FollowMode::Tail);
3382
3383 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3384 view.clone().into_any_element()
3385 });
3386 assert!(state.is_following_tail());
3387
3388 cx.simulate_event(ScrollEvent {
3390 position: point(px(50.), px(100.)),
3391 delta: ScrollDelta::Pixels(point(px(0.), px(50.))),
3392 ..Default::default()
3393 });
3394 assert!(!state.is_following_tail());
3395
3396 cx.simulate_event(ScrollEvent {
3398 position: point(px(50.), px(100.)),
3399 delta: ScrollDelta::Pixels(point(px(0.), px(-10000.))),
3400 ..Default::default()
3401 });
3402
3403 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3406 view.clone().into_any_element()
3407 });
3408 assert!(
3409 state.is_following_tail(),
3410 "follow_tail should re-engage after scrolling back to the bottom"
3411 );
3412 }
3413
3414 #[gpui::test]
3417 fn test_follow_tail_reengagement_not_fooled_by_unmeasured_items(cx: &mut TestAppContext) {
3418 let cx = cx.add_empty_window();
3419
3420 let state = ListState::new(20, crate::ListAlignment::Top, px(1000.));
3424
3425 struct TestView(ListState);
3426 impl Render for TestView {
3427 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3428 list(self.0.clone(), |_, _, _| {
3429 div().h(px(50.)).w_full().into_any()
3430 })
3431 .w_full()
3432 .h_full()
3433 }
3434 }
3435
3436 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3437
3438 state.set_follow_mode(FollowMode::Tail);
3439
3440 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3441 view.clone().into_any_element()
3442 });
3443 assert!(state.is_following_tail());
3444
3445 cx.simulate_event(ScrollEvent {
3449 position: point(px(50.), px(100.)),
3450 delta: ScrollDelta::Pixels(point(px(0.), px(200.))),
3451 ..Default::default()
3452 });
3453 assert!(!state.is_following_tail());
3454
3455 state.remeasure_items(19..20);
3459
3460 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3466 view.clone().into_any_element()
3467 });
3468 assert!(
3469 !state.is_following_tail(),
3470 "follow_tail should not falsely re-engage due to an unmeasured item \
3471 reducing items.summary().height"
3472 );
3473 }
3474
3475 #[gpui::test]
3476 fn test_follow_tail_reengages_after_scrollbar_disengagement(cx: &mut TestAppContext) {
3477 let cx = cx.add_empty_window();
3478
3479 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3481
3482 struct TestView(ListState);
3483 impl Render for TestView {
3484 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3485 list(self.0.clone(), |_, _, _| {
3486 div().h(px(50.)).w_full().into_any()
3487 })
3488 .w_full()
3489 .h_full()
3490 }
3491 }
3492
3493 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3494
3495 state.set_follow_mode(FollowMode::Tail);
3496 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3497 view.clone().into_any_element()
3498 });
3499 assert!(state.is_following_tail());
3500
3501 state.set_offset_from_scrollbar(point(px(0.), px(-150.)));
3503 assert!(!state.is_following_tail());
3504
3505 state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
3508 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3509 view.into_any_element()
3510 });
3511 assert!(
3512 state.is_following_tail(),
3513 "follow_tail should re-engage after scrolling back to the bottom via the scrollbar"
3514 );
3515 }
3516
3517 #[gpui::test]
3518 fn test_follow_tail_reengages_after_scrollbar_drag_to_bottom_while_growing(
3519 cx: &mut TestAppContext,
3520 ) {
3521 let cx = cx.add_empty_window();
3522
3523 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3524
3525 struct TestView(ListState);
3526 impl Render for TestView {
3527 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3528 list(self.0.clone(), |_, _, _| {
3529 div().h(px(50.)).w_full().into_any()
3530 })
3531 .w_full()
3532 .h_full()
3533 }
3534 }
3535
3536 let view = cx.update(|_, cx| cx.new(|_| TestView(state.clone())));
3537
3538 state.set_follow_mode(FollowMode::Tail);
3539 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3540 view.clone().into_any_element()
3541 });
3542 assert!(state.is_following_tail());
3543
3544 state.scrollbar_drag_started();
3545
3546 state.splice(10..10, 10);
3547 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3548 view.clone().into_any_element()
3549 });
3550
3551 state.set_offset_from_scrollbar(point(px(0.), px(-300.)));
3552 state.scrollbar_drag_ended();
3553
3554 cx.draw(point(px(0.), px(0.)), size(px(100.), px(200.)), |_, _| {
3555 view.into_any_element()
3556 });
3557
3558 assert!(
3559 state.is_following_tail(),
3560 "follow_tail should re-engage when the user drags the scrollbar to \
3561 the bottom of its track, even when content has grown during the drag \
3562 (so frozen_bottom < live_bottom)"
3563 );
3564 }
3565
3566 #[gpui::test]
3567 fn test_horizontal_padding_insets_items(cx: &mut TestAppContext) {
3568 let cx = cx.add_empty_window();
3569
3570 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3571 let item_bounds = Rc::new(RefCell::new(Vec::new()));
3572
3573 struct TestView {
3574 state: ListState,
3575 item_bounds: Rc<RefCell<Vec<Bounds<Pixels>>>>,
3576 }
3577 impl Render for TestView {
3578 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3579 let item_bounds = self.item_bounds.clone();
3580 list(self.state.clone(), move |_, _, _| {
3581 let item_bounds = item_bounds.clone();
3582 canvas(
3583 move |bounds, _, _| item_bounds.borrow_mut().push(bounds),
3584 |_, _, _, _| {},
3585 )
3586 .w_full()
3587 .aspect_ratio(2.)
3588 .into_any()
3589 })
3590 .pl(px(10.))
3591 .pr(px(30.))
3592 .w_full()
3593 .h_full()
3594 }
3595 }
3596
3597 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
3598 cx.new(|_| TestView {
3599 state: state.clone(),
3600 item_bounds: item_bounds.clone(),
3601 })
3602 .into_any_element()
3603 });
3604
3605 for bounds in item_bounds.borrow().iter() {
3606 assert_eq!(bounds.origin.x, px(10.));
3607 assert_eq!(bounds.size.width, px(60.));
3608 }
3609 assert_eq!(state.max_offset_for_scrollbar().y, px(200.));
3611 }
3612
3613 #[gpui::test]
3614 fn test_inferred_width_includes_horizontal_padding(cx: &mut TestAppContext) {
3615 let cx = cx.add_empty_window();
3616
3617 let state = ListState::new(2, crate::ListAlignment::Top, px(10.));
3618 let full_width_item_bounds = Rc::new(RefCell::new(None));
3619
3620 struct TestView {
3621 state: ListState,
3622 full_width_item_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
3623 }
3624 impl Render for TestView {
3625 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3626 let full_width_item_bounds = self.full_width_item_bounds.clone();
3627 div().flex().size_full().child(
3628 list(self.state.clone(), move |ix, _, _| {
3629 if ix == 0 {
3630 div().w(px(50.)).h(px(20.)).into_any()
3631 } else {
3632 let full_width_item_bounds = full_width_item_bounds.clone();
3633 canvas(
3634 move |bounds, _, _| {
3635 *full_width_item_bounds.borrow_mut() = Some(bounds)
3636 },
3637 |_, _, _, _| {},
3638 )
3639 .h(px(20.))
3640 .w_full()
3641 .into_any()
3642 }
3643 })
3644 .with_sizing_behavior(ListSizingBehavior::Infer)
3645 .pl(px(10.))
3646 .pr(px(30.))
3647 .h_full(),
3648 )
3649 }
3650 }
3651
3652 cx.draw(point(px(0.), px(0.)), size(px(200.), px(100.)), |_, cx| {
3653 cx.new(|_| TestView {
3654 state: state.clone(),
3655 full_width_item_bounds: full_width_item_bounds.clone(),
3656 })
3657 .into_any_element()
3658 });
3659
3660 let bounds = full_width_item_bounds
3661 .borrow()
3662 .expect("item 1 was not painted");
3663 assert_eq!(bounds.origin.x, px(10.));
3664 assert_eq!(bounds.size.width, px(50.));
3665 }
3666
3667 #[gpui::test]
3668 fn test_autoscroll_above_item_top_with_horizontal_padding(cx: &mut TestAppContext) {
3669 let cx = cx.add_empty_window();
3670
3671 let state = ListState::new(5, crate::ListAlignment::Top, px(0.));
3672 state.scroll_to(gpui::ListOffset {
3673 item_ix: 2,
3674 offset_in_item: px(0.),
3675 });
3676
3677 struct TestView(ListState);
3678 impl Render for TestView {
3679 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3680 list(self.0.clone(), |ix, _, _| {
3681 if ix == 2 {
3682 canvas(
3683 |bounds, window, _| {
3684 window.request_autoscroll(Bounds::from_corners(
3685 point(bounds.left(), bounds.top() - px(30.)),
3686 point(bounds.right(), bounds.top() + px(5.)),
3687 ));
3688 },
3689 |_, _, _, _| {},
3690 )
3691 .w_full()
3692 .aspect_ratio(2.)
3693 .into_any()
3694 } else {
3695 div().w_full().aspect_ratio(2.).into_any()
3696 }
3697 })
3698 .pl(px(10.))
3699 .pr(px(30.))
3700 .w_full()
3701 .h_full()
3702 }
3703 }
3704
3705 cx.draw(point(px(0.), px(0.)), size(px(100.), px(60.)), |_, cx| {
3706 cx.new(|_| TestView(state.clone())).into_any_element()
3707 });
3708
3709 let scroll_top = state.logical_scroll_top();
3711 assert_eq!(scroll_top.item_ix, 1);
3712 assert_eq!(scroll_top.offset_in_item, px(0.));
3713 }
3714
3715 #[gpui::test]
3716 fn test_horizontal_padding_change_remeasures_items(cx: &mut TestAppContext) {
3717 let cx = cx.add_empty_window();
3718
3719 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3720
3721 struct TestView {
3722 state: ListState,
3723 padding_right: Pixels,
3724 }
3725 impl Render for TestView {
3726 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3727 list(self.state.clone(), |_, _, _| {
3728 div().w_full().aspect_ratio(2.).into_any()
3729 })
3730 .pl(px(10.))
3731 .pr(self.padding_right)
3732 .w_full()
3733 .h_full()
3734 }
3735 }
3736
3737 for (padding_right, expected_max_offset) in [(px(30.), px(200.)), (px(10.), px(300.))] {
3740 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
3741 cx.new(|_| TestView {
3742 state: state.clone(),
3743 padding_right,
3744 })
3745 .into_any_element()
3746 });
3747 assert_eq!(state.max_offset_for_scrollbar().y, expected_max_offset);
3748 }
3749 }
3750
3751 #[gpui::test]
3752 fn test_border_and_padding_inset_items(cx: &mut TestAppContext) {
3753 let cx = cx.add_empty_window();
3754
3755 let state = ListState::new(10, crate::ListAlignment::Top, px(0.)).measure_all();
3756 let item_bounds = Rc::new(RefCell::new(Vec::new()));
3757
3758 struct TestView {
3759 state: ListState,
3760 item_bounds: Rc<RefCell<Vec<Bounds<Pixels>>>>,
3761 }
3762 impl Render for TestView {
3763 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3764 let item_bounds = self.item_bounds.clone();
3765 list(self.state.clone(), move |_, _, _| {
3766 let item_bounds = item_bounds.clone();
3767 canvas(
3768 move |bounds, _, _| item_bounds.borrow_mut().push(bounds),
3769 |_, _, _, _| {},
3770 )
3771 .w_full()
3772 .aspect_ratio(2.)
3773 .into_any()
3774 })
3775 .border_l_4()
3776 .pl(px(6.))
3777 .border_r_8()
3778 .pr(px(22.))
3779 .w_full()
3780 .h_full()
3781 }
3782 }
3783
3784 cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
3785 cx.new(|_| TestView {
3786 state: state.clone(),
3787 item_bounds: item_bounds.clone(),
3788 })
3789 .into_any_element()
3790 });
3791
3792 let painted_bounds = item_bounds.borrow();
3793 assert!(!painted_bounds.is_empty());
3794 for bounds in painted_bounds.iter() {
3795 assert_eq!(bounds.origin.x, px(10.));
3796 assert_eq!(bounds.size.width, px(60.));
3797 }
3798 assert_eq!(state.max_offset_for_scrollbar().y, px(200.));
3799
3800 let reported_bounds = state.bounds_for_item(0).expect("item 0 should be measured");
3801 assert_eq!(reported_bounds.origin.x, px(10.));
3802 assert_eq!(reported_bounds.size.width, px(60.));
3803 }
3804
3805 fn draw_list(
3806 state: &ListState,
3807 viewport_height: f32,
3808 render_item: impl Fn(usize) -> AnyElement + 'static,
3809 cx: &mut VisualTestContext,
3810 ) {
3811 cx.draw(
3812 point(px(0.), px(0.)),
3813 size(px(100.), px(viewport_height)),
3814 |_, cx| {
3815 cx.new(|_| TestView {
3816 state: state.clone(),
3817 render_item: Rc::new(render_item),
3818 })
3819 .into_any_element()
3820 },
3821 );
3822 }
3823
3824 fn painted_item(
3825 index: usize,
3826 height: f32,
3827 painted: &Rc<RefCell<Vec<(usize, Pixels, Pixels)>>>,
3828 ) -> AnyElement {
3829 let painted = painted.clone();
3830 canvas(
3831 |_, _, _| {},
3832 move |bounds, _, _, _| {
3833 painted
3834 .borrow_mut()
3835 .push((index, bounds.top(), bounds.bottom()));
3836 },
3837 )
3838 .h(px(height))
3839 .w_full()
3840 .into_any()
3841 }
3842
3843 fn item_readiness(state: &ListState, ready: bool) -> Rc<Cell<bool>> {
3844 let ready = Rc::new(Cell::new(ready));
3845 state.set_item_measurement_readiness({
3846 let ready = ready.clone();
3847 move |_, _| ready.get()
3848 });
3849 ready
3850 }
3851
3852 fn list_offset(item_ix: usize, offset: f32) -> ListOffset {
3853 ListOffset {
3854 item_ix,
3855 offset_in_item: px(offset),
3856 }
3857 }
3858
3859 struct TestView {
3860 state: ListState,
3861 render_item: Rc<dyn Fn(usize) -> AnyElement>,
3862 }
3863
3864 impl Render for TestView {
3865 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3866 let render_item = self.render_item.clone();
3867 list(self.state.clone(), move |index, _, _| render_item(index))
3868 .w_full()
3869 .h_full()
3870 }
3871 }
3872
3873 struct TestListView(ListState);
3874 impl Render for TestListView {
3875 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3876 list(self.0.clone(), |_, _, _| {
3877 div().h(px(20.)).w_full().into_any()
3878 })
3879 .w_full()
3880 .h_full()
3881 }
3882 }
3883}