1use crate::{
9 AnyElement, App, AvailableSpace, Bounds, ContentMask, Element, ElementId, Entity,
10 GlobalElementId, Hitbox, InspectorElementId, InteractiveElement, Interactivity, IntoElement,
11 IsZero, LayoutId, ListSizingBehavior, Overflow, Pixels, Point, ScrollHandle, Size,
12 StyleRefinement, Styled, Window, point, px, size,
13};
14use smallvec::SmallVec;
15use std::{cell::RefCell, cmp, ops::Range, rc::Rc};
16
17use super::ListHorizontalSizingBehavior;
18
19#[track_caller]
23pub fn uniform_list<R>(
24 id: impl Into<ElementId>,
25 item_count: usize,
26 f: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
27) -> UniformList
28where
29 R: IntoElement,
30{
31 let id = id.into();
32 let mut base_style = StyleRefinement::default();
33 base_style.overflow.y = Some(Overflow::Scroll);
34
35 let render_range = move |range: Range<usize>, window: &mut Window, cx: &mut App| {
36 f(range, window, cx)
37 .into_iter()
38 .map(|component| component.into_any_element())
39 .collect()
40 };
41
42 UniformList {
43 item_count,
44 item_to_measure_index: 0,
45 render_items: Box::new(render_range),
46 decorations: Vec::new(),
47 interactivity: Interactivity {
48 element_id: Some(id),
49 base_style: Box::new(base_style),
50 ..Interactivity::new()
51 },
52 scroll_handle: None,
53 sizing_behavior: ListSizingBehavior::default(),
54 horizontal_sizing_behavior: ListHorizontalSizingBehavior::default(),
55 }
56}
57
58pub struct UniformList {
60 item_count: usize,
61 item_to_measure_index: usize,
62 render_items: Box<
63 dyn for<'a> Fn(Range<usize>, &'a mut Window, &'a mut App) -> SmallVec<[AnyElement; 64]>,
64 >,
65 decorations: Vec<Box<dyn UniformListDecoration>>,
66 interactivity: Interactivity,
67 scroll_handle: Option<UniformListScrollHandle>,
68 sizing_behavior: ListSizingBehavior,
69 horizontal_sizing_behavior: ListHorizontalSizingBehavior,
70}
71
72pub struct UniformListFrameState {
74 items: SmallVec<[AnyElement; 32]>,
75 decorations: SmallVec<[AnyElement; 2]>,
76}
77
78#[derive(Clone, Debug, Default)]
81pub struct UniformListScrollHandle(pub Rc<RefCell<UniformListScrollState>>);
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85pub enum ScrollStrategy {
86 Top,
88 Center,
92 Bottom,
96 Nearest,
100}
101
102#[derive(Clone, Copy, Debug)]
103#[allow(missing_docs)]
104pub struct DeferredScrollToItem {
105 pub item_index: usize,
107 pub strategy: ScrollStrategy,
109 pub offset: usize,
111 pub scroll_strict: bool,
112}
113
114#[derive(Clone, Debug, Default)]
115#[allow(missing_docs)]
116pub struct UniformListScrollState {
117 pub base_handle: ScrollHandle,
118 pub deferred_scroll_to_item: Option<DeferredScrollToItem>,
119 pub last_item_size: Option<ItemSize>,
121 pub y_flipped: bool,
123}
124
125#[derive(Copy, Clone, Debug, Default)]
126pub struct ItemSize {
128 pub item: Size<Pixels>,
130 pub contents: Size<Pixels>,
133}
134
135impl UniformListScrollHandle {
136 pub fn new() -> Self {
138 Self(Rc::new(RefCell::new(UniformListScrollState {
139 base_handle: ScrollHandle::new(),
140 deferred_scroll_to_item: None,
141 last_item_size: None,
142 y_flipped: false,
143 })))
144 }
145
146 pub fn scroll_to_item(&self, ix: usize, strategy: ScrollStrategy) {
152 crate::fast::dependencies::scroll_handle_changed(&self.0.borrow().base_handle);
153 self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
154 item_index: ix,
155 strategy,
156 offset: 0,
157 scroll_strict: false,
158 });
159 }
160
161 pub fn scroll_to_item_strict(&self, ix: usize, strategy: ScrollStrategy) {
166 crate::fast::dependencies::scroll_handle_changed(&self.0.borrow().base_handle);
167 self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
168 item_index: ix,
169 strategy,
170 offset: 0,
171 scroll_strict: true,
172 });
173 }
174
175 pub fn scroll_to_item_with_offset(&self, ix: usize, strategy: ScrollStrategy, offset: usize) {
186 crate::fast::dependencies::scroll_handle_changed(&self.0.borrow().base_handle);
187 self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
188 item_index: ix,
189 strategy,
190 offset,
191 scroll_strict: false,
192 });
193 }
194
195 pub fn scroll_to_item_strict_with_offset(
206 &self,
207 ix: usize,
208 strategy: ScrollStrategy,
209 offset: usize,
210 ) {
211 crate::fast::dependencies::scroll_handle_changed(&self.0.borrow().base_handle);
212 self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
213 item_index: ix,
214 strategy,
215 offset,
216 scroll_strict: true,
217 });
218 }
219
220 pub fn y_flipped(&self) -> bool {
222 self.0.borrow().y_flipped
223 }
224
225 #[cfg(any(test, feature = "test-support"))]
227 pub fn logical_scroll_top_index(&self) -> usize {
228 let this = self.0.borrow();
229 this.deferred_scroll_to_item
230 .as_ref()
231 .map(|deferred| deferred.item_index)
232 .unwrap_or_else(|| this.base_handle.logical_scroll_top().0)
233 }
234
235 pub fn is_scrollable(&self) -> bool {
237 if let Some(size) = self.0.borrow().last_item_size {
238 size.contents.height > size.item.height
239 } else {
240 false
241 }
242 }
243
244 pub fn is_scrolled_to_end(&self) -> Option<bool> {
247 let state = self.0.borrow();
248 let max_offset = state.base_handle.max_offset();
249 if max_offset.y <= px(0.) {
250 return None;
251 }
252 let offset = state.base_handle.offset();
253 Some(-offset.y >= max_offset.y)
254 }
255
256 pub fn scroll_to_bottom(&self) {
258 self.scroll_to_item(usize::MAX, ScrollStrategy::Bottom);
259 }
260}
261
262impl Styled for UniformList {
263 fn style(&mut self) -> &mut StyleRefinement {
264 &mut self.interactivity.base_style
265 }
266}
267
268impl Element for UniformList {
269 type RequestLayoutState = UniformListFrameState;
270 type PrepaintState = Option<Hitbox>;
271
272 fn id(&self) -> Option<ElementId> {
273 self.interactivity.element_id.clone()
274 }
275
276 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
277 None
278 }
279
280 fn request_layout(
281 &mut self,
282 global_id: Option<&GlobalElementId>,
283 inspector_id: Option<&InspectorElementId>,
284 window: &mut Window,
285 cx: &mut App,
286 ) -> (LayoutId, Self::RequestLayoutState) {
287 let max_items = self.item_count;
288 let item_size = self.measure_item(None, window, cx);
289 let layout_id = self.interactivity.request_layout(
290 global_id,
291 inspector_id,
292 window,
293 cx,
294 |style, window, cx| match self.sizing_behavior {
295 ListSizingBehavior::Infer => {
296 window.with_text_style(style.text_style().cloned(), |window| {
297 window.request_measured_layout(
298 style,
299 move |known_dimensions, available_space, _window, _cx| {
300 let desired_height = item_size.height * max_items;
301 let width = known_dimensions.width.unwrap_or(match available_space
302 .width
303 {
304 AvailableSpace::Definite(x) => x,
305 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
306 item_size.width
307 }
308 });
309 let height = match available_space.height {
310 AvailableSpace::Definite(height) => desired_height.min(height),
311 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
312 desired_height
313 }
314 };
315 size(width, height)
316 },
317 )
318 })
319 }
320 ListSizingBehavior::Auto => window
321 .with_text_style(style.text_style().cloned(), |window| {
322 window.request_layout(style, None, cx)
323 }),
324 },
325 );
326
327 (
328 layout_id,
329 UniformListFrameState {
330 items: SmallVec::new(),
331 decorations: SmallVec::new(),
332 },
333 )
334 }
335
336 fn prepaint(
337 &mut self,
338 global_id: Option<&GlobalElementId>,
339 inspector_id: Option<&InspectorElementId>,
340 bounds: Bounds<Pixels>,
341 frame_state: &mut Self::RequestLayoutState,
342 window: &mut Window,
343 cx: &mut App,
344 ) -> Option<Hitbox> {
345 let style = self
346 .interactivity
347 .compute_style(global_id, None, window, cx);
348 let border = style.border_widths.to_pixels(window.rem_size());
349 let padding = style
350 .padding
351 .to_pixels(bounds.size.into(), window.rem_size());
352
353 let padded_bounds = Bounds::from_corners(
354 bounds.origin + point(border.left + padding.left, border.top + padding.top),
355 bounds.bottom_right()
356 - point(border.right + padding.right, border.bottom + padding.bottom),
357 );
358
359 let can_scroll_horizontally = matches!(
360 self.horizontal_sizing_behavior,
361 ListHorizontalSizingBehavior::Unconstrained
362 );
363
364 let longest_item_size =
365 crate::fast::layers::lists::measure_item(window, cx, global_id, |window, cx| {
366 self.measure_item(None, window, cx)
367 });
368 let content_width = if can_scroll_horizontally {
369 padded_bounds.size.width.max(longest_item_size.width)
370 } else {
371 padded_bounds.size.width
372 };
373 let content_size = Size {
374 width: content_width,
375 height: longest_item_size.height * self.item_count,
376 };
377
378 let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
379 let item_height = longest_item_size.height;
380 let shared_scroll_to_item = self.scroll_handle.as_mut().and_then(|handle| {
381 let mut handle = handle.0.borrow_mut();
382 handle.last_item_size = Some(ItemSize {
383 item: padded_bounds.size,
384 contents: content_size,
385 });
386 handle.deferred_scroll_to_item.take()
387 });
388
389 self.interactivity.prepaint(
390 global_id,
391 inspector_id,
392 bounds,
393 content_size,
394 window,
395 cx,
396 |_style, mut scroll_offset, hitbox, window, cx| {
397 let y_flipped = if let Some(scroll_handle) = &self.scroll_handle {
398 let scroll_state = scroll_handle.0.borrow();
399 scroll_state.y_flipped
400 } else {
401 false
402 };
403
404 if self.item_count > 0 {
405 let content_height = item_height * self.item_count;
406
407 let is_scrolled_vertically = !scroll_offset.y.is_zero();
408 let max_scroll_offset = padded_bounds.size.height - content_height;
409
410 if is_scrolled_vertically && scroll_offset.y < max_scroll_offset {
411 shared_scroll_offset.borrow_mut().y = max_scroll_offset;
412 scroll_offset.y = max_scroll_offset;
413 }
414
415 let content_width = content_size.width + padding.left + padding.right;
416 let is_scrolled_horizontally =
417 can_scroll_horizontally && !scroll_offset.x.is_zero();
418 if is_scrolled_horizontally && content_width <= padded_bounds.size.width {
419 shared_scroll_offset.borrow_mut().x = Pixels::ZERO;
420 scroll_offset.x = Pixels::ZERO;
421 }
422
423 if let Some(DeferredScrollToItem {
424 mut item_index,
425 mut strategy,
426 offset,
427 scroll_strict,
428 }) = shared_scroll_to_item
429 {
430 if y_flipped {
431 item_index = self.item_count.saturating_sub(item_index + 1);
432 }
433 let list_height = padded_bounds.size.height;
434 let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
435 let item_top = item_height * item_index;
436 let item_bottom = item_top + item_height;
437 let scroll_top = -updated_scroll_offset.y;
438 let offset_pixels = item_height * offset;
439
440 let is_above = item_top < scroll_top + offset_pixels;
442 let is_below = item_bottom > scroll_top + list_height;
443
444 if scroll_strict || is_above || is_below {
445 if strategy == ScrollStrategy::Nearest {
446 if is_above {
447 strategy = ScrollStrategy::Top;
448 } else if is_below {
449 strategy = ScrollStrategy::Bottom;
450 }
451 }
452
453 let max_scroll_offset =
454 (content_height - list_height).max(Pixels::ZERO);
455 match strategy {
456 ScrollStrategy::Top => {
457 updated_scroll_offset.y = -(item_top - offset_pixels)
458 .clamp(Pixels::ZERO, max_scroll_offset);
459 }
460 ScrollStrategy::Center => {
461 let item_center = item_top + item_height / 2.0;
462
463 let viewport_height = list_height - offset_pixels;
464 let viewport_center = offset_pixels + viewport_height / 2.0;
465 let target_scroll_top = item_center - viewport_center;
466 updated_scroll_offset.y =
467 -target_scroll_top.clamp(Pixels::ZERO, max_scroll_offset);
468 }
469 ScrollStrategy::Bottom => {
470 updated_scroll_offset.y = -(item_bottom - list_height)
471 .clamp(Pixels::ZERO, max_scroll_offset);
472 }
473 ScrollStrategy::Nearest => {
474 }
476 }
477 }
478 scroll_offset = *updated_scroll_offset
479 }
480
481 let scroll_offset =
482 crate::fast::layers::lists::snap_item_offset(window, scroll_offset);
483 let scroll_top = -scroll_offset.y.to_f64();
484 let item_height_f64 = item_height.to_f64();
485 let first_visible_element_ix =
486 ((scroll_top - padding.top.to_f64()) / item_height_f64).floor() as usize;
487 let last_visible_element_ix = ((scroll_top
488 + padded_bounds.size.height.to_f64())
489 / item_height_f64)
490 .ceil() as usize;
491
492 let visible_range = first_visible_element_ix
493 ..cmp::min(last_visible_element_ix, self.item_count);
494 let fast_rows = crate::fast::layers::lists::begin_uniform_list(
495 window,
496 cx,
497 global_id,
498 padded_bounds,
499 scroll_offset,
500 item_height,
501 self.item_count,
502 &visible_range,
503 y_flipped,
504 );
505
506 let items = if y_flipped {
507 let flipped_range = self.item_count.saturating_sub(visible_range.end)
508 ..self.item_count.saturating_sub(visible_range.start);
509 let mut items = (self.render_items)(flipped_range, window, cx);
510 items.reverse();
511 items
512 } else {
513 crate::fast::layers::lists::render_rows(
514 &fast_rows,
515 visible_range.clone(),
516 |range| (self.render_items)(range, window, cx),
517 )
518 };
519
520 let fast_indices =
521 crate::fast::layers::lists::row_indices(&fast_rows, visible_range.clone());
522 let content_mask = ContentMask { bounds };
523 window.with_content_mask(Some(content_mask), |window| {
524 for (mut item, ix) in items.into_iter().zip(fast_indices) {
525 let item_top = item_height_f64 * ix as f64 - scroll_top;
526 let item_origin = padded_bounds.origin
527 + point(scroll_offset.x, Pixels::from(item_top));
528
529 let available_width = if can_scroll_horizontally {
530 padded_bounds.size.width + scroll_offset.x.abs()
531 } else {
532 padded_bounds.size.width
533 };
534 let available_space = size(
535 AvailableSpace::Definite(available_width),
536 AvailableSpace::Definite(item_height),
537 );
538 crate::fast::layout_key::layout_as_list_item(
539 &mut item,
540 ix,
541 available_space,
542 window,
543 cx,
544 );
545 crate::fast::layers::lists::prepaint_row(
546 window,
547 cx,
548 ix,
549 |window, cx| item.prepaint_at(item_origin, window, cx),
550 );
551 frame_state.items.push(item);
552 }
553 crate::fast::layers::lists::end_rows(window, cx, global_id, fast_rows);
554
555 let bounds =
556 Bounds::new(padded_bounds.origin + scroll_offset, padded_bounds.size);
557 for decoration in &self.decorations {
558 let mut decoration = decoration.as_ref().compute(
559 visible_range.clone(),
560 bounds,
561 scroll_offset,
562 item_height,
563 self.item_count,
564 window,
565 cx,
566 );
567 let available_space = size(
568 AvailableSpace::Definite(bounds.size.width),
569 AvailableSpace::Definite(bounds.size.height),
570 );
571 decoration.layout_as_root(available_space, window, cx);
572 decoration.prepaint_at(bounds.origin, window, cx);
573 frame_state.decorations.push(decoration);
574 }
575 });
576 }
577
578 hitbox
579 },
580 )
581 }
582
583 fn paint(
584 &mut self,
585 global_id: Option<&GlobalElementId>,
586 inspector_id: Option<&InspectorElementId>,
587 bounds: Bounds<crate::Pixels>,
588 request_layout: &mut Self::RequestLayoutState,
589 hitbox: &mut Option<Hitbox>,
590 window: &mut Window,
591 cx: &mut App,
592 ) {
593 self.interactivity.paint(
594 global_id,
595 inspector_id,
596 bounds,
597 hitbox.as_ref(),
598 window,
599 cx,
600 |_, window, cx| {
601 crate::fast::layers::lists::begin_paint_rows(window, cx, global_id);
602 for item in &mut request_layout.items {
603 crate::fast::layers::lists::paint_row(window, cx, None, |window, cx| {
604 item.paint(window, cx)
605 });
606 }
607 crate::fast::layers::lists::end_paint_rows(window, cx, global_id);
608 for decoration in &mut request_layout.decorations {
609 decoration.paint(window, cx);
610 }
611 },
612 )
613 }
614}
615
616pub trait UniformListDecoration {
619 fn compute(
622 &self,
623 visible_range: Range<usize>,
624 bounds: Bounds<Pixels>,
625 scroll_offset: Point<Pixels>,
626 item_height: Pixels,
627 item_count: usize,
628 window: &mut Window,
629 cx: &mut App,
630 ) -> AnyElement;
631}
632
633impl<T: UniformListDecoration + 'static> UniformListDecoration for Entity<T> {
634 fn compute(
635 &self,
636 visible_range: Range<usize>,
637 bounds: Bounds<Pixels>,
638 scroll_offset: Point<Pixels>,
639 item_height: Pixels,
640 item_count: usize,
641 window: &mut Window,
642 cx: &mut App,
643 ) -> AnyElement {
644 self.update(cx, |inner, cx| {
645 inner.compute(
646 visible_range,
647 bounds,
648 scroll_offset,
649 item_height,
650 item_count,
651 window,
652 cx,
653 )
654 })
655 }
656}
657
658impl UniformList {
659 pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
661 self.item_to_measure_index = item_index.unwrap_or(0);
662 self
663 }
664
665 pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
667 self.sizing_behavior = behavior;
668 self
669 }
670
671 pub fn with_horizontal_sizing_behavior(
675 mut self,
676 behavior: ListHorizontalSizingBehavior,
677 ) -> Self {
678 self.horizontal_sizing_behavior = behavior;
679 match behavior {
680 ListHorizontalSizingBehavior::FitList => {
681 self.interactivity.base_style.overflow.x = None;
682 }
683 ListHorizontalSizingBehavior::Unconstrained => {
684 self.interactivity.base_style.overflow.x = Some(Overflow::Scroll);
685 }
686 }
687 self
688 }
689
690 pub fn with_decoration(mut self, decoration: impl UniformListDecoration + 'static) -> Self {
692 self.decorations.push(Box::new(decoration));
693 self
694 }
695
696 fn measure_item(
697 &self,
698 list_width: Option<Pixels>,
699 window: &mut Window,
700 cx: &mut App,
701 ) -> Size<Pixels> {
702 if self.item_count == 0 {
703 return Size::default();
704 }
705
706 let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
707 let mut items = (self.render_items)(item_ix..item_ix + 1, window, cx);
708 let Some(mut item_to_measure) = items.pop() else {
709 return Size::default();
710 };
711 let available_space = size(
712 list_width.map_or(AvailableSpace::MaxContent, |width| {
713 AvailableSpace::Definite(width)
714 }),
715 AvailableSpace::MinContent,
716 );
717 item_to_measure.layout_as_root(available_space, window, cx)
718 }
719
720 pub fn track_scroll(mut self, handle: &UniformListScrollHandle) -> Self {
722 self.interactivity.tracked_scroll_handle = Some(handle.0.borrow().base_handle.clone());
723 self.scroll_handle = Some(handle.clone());
724 self
725 }
726
727 pub fn y_flipped(self, y_flipped: bool) -> Self {
729 if let Some(ref scroll_handle) = self.scroll_handle {
730 let mut scroll_state = scroll_handle.0.borrow_mut();
731 let base_handle = &scroll_state.base_handle;
732 let offset = base_handle.offset();
733 match scroll_state.last_item_size {
734 Some(last_size) if scroll_state.y_flipped != y_flipped => {
735 let new_y_offset =
736 -(offset.y + last_size.contents.height - last_size.item.height);
737 base_handle.set_offset(point(offset.x, new_y_offset));
738 scroll_state.y_flipped = y_flipped;
739 }
740 None if y_flipped => {
742 base_handle.set_offset(point(offset.x, Pixels::MIN));
743 scroll_state.y_flipped = y_flipped;
744 }
745 _ => {}
746 }
747 }
748 self
749 }
750}
751
752impl InteractiveElement for UniformList {
753 fn interactivity(&mut self) -> &mut crate::Interactivity {
754 &mut self.interactivity
755 }
756}
757
758#[cfg(test)]
759mod test {
760 use crate::TestAppContext;
761
762 #[gpui::test]
763 fn test_scroll_strategy_nearest(cx: &mut TestAppContext) {
764 use crate::{
765 Context, FocusHandle, ScrollStrategy, UniformListScrollHandle, Window, div, prelude::*,
766 px, uniform_list,
767 };
768 use std::ops::Range;
769
770 actions!(example, [SelectNext, SelectPrev]);
771
772 struct TestView {
773 index: usize,
774 length: usize,
775 scroll_handle: UniformListScrollHandle,
776 focus_handle: FocusHandle,
777 visible_range: Range<usize>,
778 }
779
780 impl TestView {
781 pub fn select_next(
782 &mut self,
783 _: &SelectNext,
784 window: &mut Window,
785 _: &mut Context<Self>,
786 ) {
787 if self.index + 1 == self.length {
788 self.index = 0
789 } else {
790 self.index += 1;
791 }
792 self.scroll_handle
793 .scroll_to_item(self.index, ScrollStrategy::Nearest);
794 window.refresh();
795 }
796
797 pub fn select_previous(
798 &mut self,
799 _: &SelectPrev,
800 window: &mut Window,
801 _: &mut Context<Self>,
802 ) {
803 if self.index == 0 {
804 self.index = self.length - 1
805 } else {
806 self.index -= 1;
807 }
808 self.scroll_handle
809 .scroll_to_item(self.index, ScrollStrategy::Nearest);
810 window.refresh();
811 }
812 }
813
814 impl Render for TestView {
815 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
816 div()
817 .id("list-example")
818 .track_focus(&self.focus_handle)
819 .on_action(cx.listener(Self::select_next))
820 .on_action(cx.listener(Self::select_previous))
821 .size_full()
822 .child(
823 uniform_list(
824 "entries",
825 self.length,
826 cx.processor(|this, range: Range<usize>, _window, _cx| {
827 this.visible_range = range.clone();
828 range
829 .map(|ix| div().id(ix).h(px(20.0)).child(format!("Item {ix}")))
830 .collect()
831 }),
832 )
833 .track_scroll(&self.scroll_handle)
834 .h(px(200.0)),
835 )
836 }
837 }
838
839 let (view, cx) = cx.add_window_view(|window, cx| {
840 let focus_handle = cx.focus_handle();
841 window.focus(&focus_handle, cx);
842 TestView {
843 scroll_handle: UniformListScrollHandle::new(),
844 index: 0,
845 focus_handle,
846 length: 47,
847 visible_range: 0..0,
848 }
849 });
850
851 for ix in 1..10 {
855 cx.dispatch_action(SelectNext);
856 view.read_with(cx, |view, _| {
857 assert_eq!(view.index, ix);
858 assert_eq!(view.visible_range, 0..10);
859 })
860 }
861
862 for ix in 10..47 {
864 cx.dispatch_action(SelectNext);
865 view.read_with(cx, |view, _| {
866 assert_eq!(view.index, ix);
867 assert_eq!(view.visible_range, ix - 9..ix + 1);
868 })
869 }
870
871 cx.dispatch_action(SelectNext);
873 view.read_with(cx, |view, _| {
874 assert_eq!(view.index, 0);
875 assert_eq!(view.visible_range, 0..10);
876 });
877
878 cx.dispatch_action(SelectPrev);
880 view.read_with(cx, |view, _| {
881 assert_eq!(view.index, 46);
882 assert_eq!(view.visible_range, 37..47);
883 });
884
885 for ix in (37..46).rev() {
887 cx.dispatch_action(SelectPrev);
888 view.read_with(cx, |view, _| {
889 assert_eq!(view.index, ix);
890 assert_eq!(view.visible_range, 37..47);
891 })
892 }
893
894 for ix in (0..37).rev() {
896 cx.dispatch_action(SelectPrev);
897 view.read_with(cx, |view, _| {
898 assert_eq!(view.index, ix);
899 assert_eq!(view.visible_range, ix..ix + 10);
900 })
901 }
902 }
903
904 #[gpui::test]
905 fn test_item_positions_far_down_long_list(cx: &mut TestAppContext) {
906 use crate::{
907 Bounds, Context, Pixels, UniformListScrollHandle, Window, canvas, point, prelude::*,
908 px, uniform_list,
909 };
910 use std::{cell::RefCell, ops::Range, rc::Rc};
911
912 struct TestView {
913 scroll_handle: UniformListScrollHandle,
914 item_bounds: Rc<RefCell<Vec<(usize, Bounds<Pixels>)>>>,
915 }
916
917 impl Render for TestView {
918 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
919 let item_bounds = self.item_bounds.clone();
920 uniform_list(
921 "entries",
922 10_000_000,
923 cx.processor(move |_, range: Range<usize>, _window, _cx| {
924 range
925 .map(|ix| {
926 let item_bounds = item_bounds.clone();
927 canvas(
928 move |bounds, _, _| item_bounds.borrow_mut().push((ix, bounds)),
929 |_, _, _, _| {},
930 )
931 .w_full()
932 .h(px(24.0))
933 })
934 .collect()
935 }),
936 )
937 .track_scroll(&self.scroll_handle)
938 .h(px(200.0))
939 }
940 }
941
942 let item_bounds = Rc::new(RefCell::new(Vec::new()));
943 let (view, cx) = cx.add_window_view(|_, _| TestView {
944 scroll_handle: UniformListScrollHandle::new(),
945 item_bounds: item_bounds.clone(),
946 });
947
948 item_bounds.borrow_mut().clear();
951 view.update(cx, |view, cx| {
952 view.scroll_handle
953 .0
954 .borrow()
955 .base_handle
956 .set_offset(point(px(0.0), px(-216_000_064.0)));
957 cx.notify();
958 });
959 cx.run_until_parked();
960
961 let item_tops = item_bounds
962 .borrow()
963 .iter()
964 .map(|(ix, bounds)| (*ix, bounds.origin.y))
965 .collect::<Vec<_>>();
966 let expected_tops = (9_000_002..9_000_011)
967 .map(|ix| (ix, px(-16.0 + 24.0 * (ix - 9_000_002) as f32)))
968 .collect::<Vec<_>>();
969 assert_eq!(item_tops, expected_tops);
970 }
971}