1//! A list element that can be used to render a large number of differently sized elements
2//! efficiently. Clients of this API need to ensure that elements outside of the scrolled
3//! area do not change their height for this element to function correctly. In order to minimize
4//! re-renders, this element's state is stored intrusively on your own views, so that your code
5//! can coordinate directly with the list element's cached state.
6//!
7//! If all of your elements are the same height, see [`UniformList`] for a simpler API
8
9use crate::{
10 point, px, size, AnyElement, AvailableSpace, Bounds, ContentMask, DispatchPhase, Edges,
11 Element, ElementContext, FocusHandle, Hitbox, IntoElement, Pixels, Point, ScrollWheelEvent,
12 Size, Style, StyleRefinement, Styled, WindowContext,
13};
14use collections::VecDeque;
15use refineable::Refineable as _;
16use std::{cell::RefCell, ops::Range, rc::Rc};
17use sum_tree::{Bias, SumTree};
18use taffy::style::Overflow;
19
20/// Construct a new list element
21pub fn list(state: ListState) -> List {
22 List {
23 state,
24 style: StyleRefinement::default(),
25 sizing_behavior: ListSizingBehavior::default(),
26 }
27}
28
29/// A list element
30pub struct List {
31 state: ListState,
32 style: StyleRefinement,
33 sizing_behavior: ListSizingBehavior,
34}
35
36impl List {
37 /// Set the sizing behavior for the list.
38 pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
39 self.sizing_behavior = behavior;
40 self
41 }
42}
43
44/// The list state that views must hold on behalf of the list element.
45#[derive(Clone)]
46pub struct ListState(Rc<RefCell<StateInner>>);
47
48struct StateInner {
49 last_layout_bounds: Option<Bounds<Pixels>>,
50 last_padding: Option<Edges<Pixels>>,
51 render_item: Box<dyn FnMut(usize, &mut WindowContext) -> AnyElement>,
52 items: SumTree<ListItem>,
53 logical_scroll_top: Option<ListOffset>,
54 alignment: ListAlignment,
55 overdraw: Pixels,
56 reset: bool,
57 #[allow(clippy::type_complexity)]
58 scroll_handler: Option<Box<dyn FnMut(&ListScrollEvent, &mut WindowContext)>>,
59}
60
61/// Whether the list is scrolling from top to bottom or bottom to top.
62#[derive(Clone, Copy, Debug, Eq, PartialEq)]
63pub enum ListAlignment {
64 /// The list is scrolling from top to bottom, like most lists.
65 Top,
66 /// The list is scrolling from bottom to top, like a chat log.
67 Bottom,
68}
69
70/// A scroll event that has been converted to be in terms of the list's items.
71pub struct ListScrollEvent {
72 /// The range of items currently visible in the list, after applying the scroll event.
73 pub visible_range: Range<usize>,
74
75 /// The number of items that are currently visible in the list, after applying the scroll event.
76 pub count: usize,
77
78 /// Whether the list has been scrolled.
79 pub is_scrolled: bool,
80}
81
82/// The sizing behavior to apply during layout.
83#[derive(Clone, Copy, Debug, Default, PartialEq)]
84pub enum ListSizingBehavior {
85 /// The list should calculate its size based on the size of its items.
86 Infer,
87 /// The list should not calculate a fixed size.
88 #[default]
89 Auto,
90}
91
92struct LayoutItemsResponse {
93 max_item_width: Pixels,
94 scroll_top: ListOffset,
95 item_layouts: VecDeque<ItemLayout>,
96}
97
98struct ItemLayout {
99 index: usize,
100 element: AnyElement,
101 size: Size<Pixels>,
102}
103
104/// Frame state used by the [List] element after layout.
105pub struct ListPrepaintState {
106 hitbox: Hitbox,
107 layout: LayoutItemsResponse,
108}
109
110#[derive(Clone)]
111enum ListItem {
112 Unmeasured {
113 focus_handle: Option<FocusHandle>,
114 },
115 Measured {
116 size: Size<Pixels>,
117 focus_handle: Option<FocusHandle>,
118 },
119}
120
121impl ListItem {
122 fn size(&self) -> Option<Size<Pixels>> {
123 if let ListItem::Measured { size, .. } = self {
124 Some(*size)
125 } else {
126 None
127 }
128 }
129
130 fn focus_handle(&self) -> Option<FocusHandle> {
131 match self {
132 ListItem::Unmeasured { focus_handle } | ListItem::Measured { focus_handle, .. } => {
133 focus_handle.clone()
134 }
135 }
136 }
137
138 fn contains_focused(&self, cx: &WindowContext) -> bool {
139 match self {
140 ListItem::Unmeasured { focus_handle } | ListItem::Measured { focus_handle, .. } => {
141 focus_handle
142 .as_ref()
143 .is_some_and(|handle| handle.contains_focused(cx))
144 }
145 }
146 }
147}
148
149#[derive(Clone, Debug, Default, PartialEq)]
150struct ListItemSummary {
151 count: usize,
152 rendered_count: usize,
153 unrendered_count: usize,
154 height: Pixels,
155 has_focus_handles: bool,
156}
157
158#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
159struct Count(usize);
160
161#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
162struct RenderedCount(usize);
163
164#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
165struct UnrenderedCount(usize);
166
167#[derive(Clone, Debug, Default)]
168struct Height(Pixels);
169
170impl ListState {
171 /// Construct a new list state, for storage on a view.
172 ///
173 /// The overdraw parameter controls how much extra space is rendered
174 /// above and below the visible area. Elements within this area will
175 /// be measured even though they are not visible. This can help ensure
176 /// that the list doesn't flicker or pop in when scrolling.
177 pub fn new<R>(
178 item_count: usize,
179 alignment: ListAlignment,
180 overdraw: Pixels,
181 render_item: R,
182 ) -> Self
183 where
184 R: 'static + FnMut(usize, &mut WindowContext) -> AnyElement,
185 {
186 let this = Self(Rc::new(RefCell::new(StateInner {
187 last_layout_bounds: None,
188 last_padding: None,
189 render_item: Box::new(render_item),
190 items: SumTree::new(),
191 logical_scroll_top: None,
192 alignment,
193 overdraw,
194 scroll_handler: None,
195 reset: false,
196 })));
197 this.splice(0..0, item_count);
198 this
199 }
200
201 /// Reset this instantiation of the list state.
202 ///
203 /// Note that this will cause scroll events to be dropped until the next paint.
204 pub fn reset(&self, element_count: usize) {
205 let old_count = {
206 let state = &mut *self.0.borrow_mut();
207 state.reset = true;
208 state.logical_scroll_top = None;
209 state.items.summary().count
210 };
211
212 self.splice(0..old_count, element_count);
213 }
214
215 /// The number of items in this list.
216 pub fn item_count(&self) -> usize {
217 self.0.borrow().items.summary().count
218 }
219
220 /// Inform the list state that the items in `old_range` have been replaced
221 /// by `count` new items that must be recalculated.
222 pub fn splice(&self, old_range: Range<usize>, count: usize) {
223 self.splice_focusable(old_range, (0..count).map(|_| None))
224 }
225
226 /// Register with the list state that the items in `old_range` have been replaced
227 /// by new items. As opposed to [`splice`], this method allows an iterator of optional focus handles
228 /// to be supplied to properly integrate with items in the list that can be focused. If a focused item
229 /// is scrolled out of view, the list will continue to render it to allow keyboard interaction.
230 pub fn splice_focusable(
231 &self,
232 old_range: Range<usize>,
233 focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
234 ) {
235 let state = &mut *self.0.borrow_mut();
236
237 let mut old_items = state.items.cursor::<Count>();
238 let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right, &());
239 old_items.seek_forward(&Count(old_range.end), Bias::Right, &());
240
241 let mut spliced_count = 0;
242 new_items.extend(
243 focus_handles.into_iter().map(|focus_handle| {
244 spliced_count += 1;
245 ListItem::Unmeasured { focus_handle }
246 }),
247 &(),
248 );
249 new_items.append(old_items.suffix(&()), &());
250 drop(old_items);
251 state.items = new_items;
252
253 if let Some(ListOffset {
254 item_ix,
255 offset_in_item,
256 }) = state.logical_scroll_top.as_mut()
257 {
258 if old_range.contains(item_ix) {
259 *item_ix = old_range.start;
260 *offset_in_item = px(0.);
261 } else if old_range.end <= *item_ix {
262 *item_ix = *item_ix - (old_range.end - old_range.start) + spliced_count;
263 }
264 }
265 }
266
267 /// Set a handler that will be called when the list is scrolled.
268 pub fn set_scroll_handler(
269 &self,
270 handler: impl FnMut(&ListScrollEvent, &mut WindowContext) + 'static,
271 ) {
272 self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
273 }
274
275 /// Get the current scroll offset, in terms of the list's items.
276 pub fn logical_scroll_top(&self) -> ListOffset {
277 self.0.borrow().logical_scroll_top()
278 }
279
280 /// Scroll the list to the given offset
281 pub fn scroll_to(&self, mut scroll_top: ListOffset) {
282 let state = &mut *self.0.borrow_mut();
283 let item_count = state.items.summary().count;
284 if scroll_top.item_ix >= item_count {
285 scroll_top.item_ix = item_count;
286 scroll_top.offset_in_item = px(0.);
287 }
288
289 state.logical_scroll_top = Some(scroll_top);
290 }
291
292 /// Scroll the list to the given item, such that the item is fully visible.
293 pub fn scroll_to_reveal_item(&self, ix: usize) {
294 let state = &mut *self.0.borrow_mut();
295
296 let mut scroll_top = state.logical_scroll_top();
297 let height = state
298 .last_layout_bounds
299 .map_or(px(0.), |bounds| bounds.size.height);
300 let padding = state.last_padding.unwrap_or_default();
301
302 if ix <= scroll_top.item_ix {
303 scroll_top.item_ix = ix;
304 scroll_top.offset_in_item = px(0.);
305 } else {
306 let mut cursor = state.items.cursor::<ListItemSummary>();
307 cursor.seek(&Count(ix + 1), Bias::Right, &());
308 let bottom = cursor.start().height + padding.top;
309 let goal_top = px(0.).max(bottom - height + padding.bottom);
310
311 cursor.seek(&Height(goal_top), Bias::Left, &());
312 let start_ix = cursor.start().count;
313 let start_item_top = cursor.start().height;
314
315 if start_ix >= scroll_top.item_ix {
316 scroll_top.item_ix = start_ix;
317 scroll_top.offset_in_item = goal_top - start_item_top;
318 }
319 }
320
321 state.logical_scroll_top = Some(scroll_top);
322 }
323
324 /// Get the bounds for the given item in window coordinates, if it's
325 /// been rendered.
326 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
327 let state = &*self.0.borrow();
328
329 let bounds = state.last_layout_bounds.unwrap_or_default();
330 let scroll_top = state.logical_scroll_top();
331 if ix < scroll_top.item_ix {
332 return None;
333 }
334
335 let mut cursor = state.items.cursor::<(Count, Height)>();
336 cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
337
338 let scroll_top = cursor.start().1 .0 + scroll_top.offset_in_item;
339
340 cursor.seek_forward(&Count(ix), Bias::Right, &());
341 if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
342 let &(Count(count), Height(top)) = cursor.start();
343 if count == ix {
344 let top = bounds.top() + top - scroll_top;
345 return Some(Bounds::from_corners(
346 point(bounds.left(), top),
347 point(bounds.right(), top + size.height),
348 ));
349 }
350 }
351 None
352 }
353}
354
355impl StateInner {
356 fn visible_range(&self, height: Pixels, scroll_top: &ListOffset) -> Range<usize> {
357 let mut cursor = self.items.cursor::<ListItemSummary>();
358 cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
359 let start_y = cursor.start().height + scroll_top.offset_in_item;
360 cursor.seek_forward(&Height(start_y + height), Bias::Left, &());
361 scroll_top.item_ix..cursor.start().count + 1
362 }
363
364 fn scroll(
365 &mut self,
366 scroll_top: &ListOffset,
367 height: Pixels,
368 delta: Point<Pixels>,
369 cx: &mut WindowContext,
370 ) {
371 // Drop scroll events after a reset, since we can't calculate
372 // the new logical scroll top without the item heights
373 if self.reset {
374 return;
375 }
376
377 let padding = self.last_padding.unwrap_or_default();
378 let scroll_max =
379 (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
380 let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
381 .max(px(0.))
382 .min(scroll_max);
383
384 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
385 self.logical_scroll_top = None;
386 } else {
387 let mut cursor = self.items.cursor::<ListItemSummary>();
388 cursor.seek(&Height(new_scroll_top), Bias::Right, &());
389 let item_ix = cursor.start().count;
390 let offset_in_item = new_scroll_top - cursor.start().height;
391 self.logical_scroll_top = Some(ListOffset {
392 item_ix,
393 offset_in_item,
394 });
395 }
396
397 if self.scroll_handler.is_some() {
398 let visible_range = self.visible_range(height, scroll_top);
399 self.scroll_handler.as_mut().unwrap()(
400 &ListScrollEvent {
401 visible_range,
402 count: self.items.summary().count,
403 is_scrolled: self.logical_scroll_top.is_some(),
404 },
405 cx,
406 );
407 }
408
409 cx.refresh();
410 }
411
412 fn logical_scroll_top(&self) -> ListOffset {
413 self.logical_scroll_top
414 .unwrap_or_else(|| match self.alignment {
415 ListAlignment::Top => ListOffset {
416 item_ix: 0,
417 offset_in_item: px(0.),
418 },
419 ListAlignment::Bottom => ListOffset {
420 item_ix: self.items.summary().count,
421 offset_in_item: px(0.),
422 },
423 })
424 }
425
426 fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
427 let mut cursor = self.items.cursor::<ListItemSummary>();
428 cursor.seek(&Count(logical_scroll_top.item_ix), Bias::Right, &());
429 cursor.start().height + logical_scroll_top.offset_in_item
430 }
431
432 fn layout_items(
433 &mut self,
434 available_width: Option<Pixels>,
435 available_height: Pixels,
436 padding: &Edges<Pixels>,
437 cx: &mut ElementContext,
438 ) -> LayoutItemsResponse {
439 let old_items = self.items.clone();
440 let mut measured_items = VecDeque::new();
441 let mut item_layouts = VecDeque::new();
442 let mut rendered_height = padding.top;
443 let mut max_item_width = px(0.);
444 let mut scroll_top = self.logical_scroll_top();
445 let mut rendered_focused_item = false;
446
447 let available_item_space = size(
448 available_width.map_or(AvailableSpace::MinContent, |width| {
449 AvailableSpace::Definite(width)
450 }),
451 AvailableSpace::MinContent,
452 );
453
454 let mut cursor = old_items.cursor::<Count>();
455
456 // Render items after the scroll top, including those in the trailing overdraw
457 cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
458 for (ix, item) in cursor.by_ref().enumerate() {
459 let visible_height = rendered_height - scroll_top.offset_in_item;
460 if visible_height >= available_height + self.overdraw {
461 break;
462 }
463
464 // Use the previously cached height and focus handle if available
465 let mut size = item.size();
466
467 // If we're within the visible area or the height wasn't cached, render and measure the item's element
468 if visible_height < available_height || size.is_none() {
469 let item_index = scroll_top.item_ix + ix;
470 let mut element = (self.render_item)(item_index, cx);
471 let element_size = element.layout_as_root(available_item_space, cx);
472 size = Some(element_size);
473 if visible_height < available_height {
474 item_layouts.push_back(ItemLayout {
475 index: item_index,
476 element,
477 size: element_size,
478 });
479 if item.contains_focused(cx) {
480 rendered_focused_item = true;
481 }
482 }
483 }
484
485 let size = size.unwrap();
486 rendered_height += size.height;
487 max_item_width = max_item_width.max(size.width);
488 measured_items.push_back(ListItem::Measured {
489 size,
490 focus_handle: item.focus_handle(),
491 });
492 }
493 rendered_height += padding.bottom;
494
495 // Prepare to start walking upward from the item at the scroll top.
496 cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
497
498 // If the rendered items do not fill the visible region, then adjust
499 // the scroll top upward.
500 if rendered_height - scroll_top.offset_in_item < available_height {
501 while rendered_height < available_height {
502 cursor.prev(&());
503 if let Some(item) = cursor.item() {
504 let item_index = cursor.start().0;
505 let mut element = (self.render_item)(item_index, cx);
506 let element_size = element.layout_as_root(available_item_space, cx);
507 let focus_handle = item.focus_handle();
508 rendered_height += element_size.height;
509 measured_items.push_front(ListItem::Measured {
510 size: element_size,
511 focus_handle,
512 });
513 item_layouts.push_front(ItemLayout {
514 index: item_index,
515 element,
516 size: element_size,
517 });
518 if item.contains_focused(cx) {
519 rendered_focused_item = true;
520 }
521 } else {
522 break;
523 }
524 }
525
526 scroll_top = ListOffset {
527 item_ix: cursor.start().0,
528 offset_in_item: rendered_height - available_height,
529 };
530
531 match self.alignment {
532 ListAlignment::Top => {
533 scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
534 self.logical_scroll_top = Some(scroll_top);
535 }
536 ListAlignment::Bottom => {
537 scroll_top = ListOffset {
538 item_ix: cursor.start().0,
539 offset_in_item: rendered_height - available_height,
540 };
541 self.logical_scroll_top = None;
542 }
543 };
544 }
545
546 // Measure items in the leading overdraw
547 let mut leading_overdraw = scroll_top.offset_in_item;
548 while leading_overdraw < self.overdraw {
549 cursor.prev(&());
550 if let Some(item) = cursor.item() {
551 let size = if let ListItem::Measured { size, .. } = item {
552 *size
553 } else {
554 let mut element = (self.render_item)(cursor.start().0, cx);
555 element.layout_as_root(available_item_space, cx)
556 };
557
558 leading_overdraw += size.height;
559 measured_items.push_front(ListItem::Measured {
560 size,
561 focus_handle: item.focus_handle(),
562 });
563 } else {
564 break;
565 }
566 }
567
568 let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
569 let mut cursor = old_items.cursor::<Count>();
570 let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right, &());
571 new_items.extend(measured_items, &());
572 cursor.seek(&Count(measured_range.end), Bias::Right, &());
573 new_items.append(cursor.suffix(&()), &());
574 self.items = new_items;
575
576 // If none of the visible items are focused, check if an off-screen item is focused
577 // and include it to be rendered after the visible items so keyboard interaction continues
578 // to work for it.
579 if !rendered_focused_item {
580 let mut cursor = self
581 .items
582 .filter::<_, Count>(|summary| summary.has_focus_handles);
583 cursor.next(&());
584 while let Some(item) = cursor.item() {
585 if item.contains_focused(cx) {
586 let item_index = cursor.start().0;
587 let mut element = (self.render_item)(cursor.start().0, cx);
588 let size = element.layout_as_root(available_item_space, cx);
589 item_layouts.push_back(ItemLayout {
590 index: item_index,
591 element,
592 size,
593 });
594 break;
595 }
596 cursor.next(&());
597 }
598 }
599
600 LayoutItemsResponse {
601 max_item_width,
602 scroll_top,
603 item_layouts,
604 }
605 }
606
607 fn prepaint_items(
608 &mut self,
609 bounds: Bounds<Pixels>,
610 padding: Edges<Pixels>,
611 cx: &mut ElementContext,
612 ) -> Result<LayoutItemsResponse, ListOffset> {
613 cx.transact(|cx| {
614 let mut layout_response =
615 self.layout_items(Some(bounds.size.width), bounds.size.height, &padding, cx);
616
617 // Avoid honoring autoscroll requests from elements other than our children.
618 cx.take_autoscroll();
619
620 // Only paint the visible items, if there is actually any space for them (taking padding into account)
621 if bounds.size.height > padding.top + padding.bottom {
622 let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
623 item_origin.y -= layout_response.scroll_top.offset_in_item;
624 for item in &mut layout_response.item_layouts {
625 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
626 item.element.prepaint_at(item_origin, cx);
627 });
628
629 if let Some(autoscroll_bounds) = cx.take_autoscroll() {
630 if bounds.intersect(&autoscroll_bounds) != autoscroll_bounds {
631 return Err(ListOffset {
632 item_ix: item.index,
633 offset_in_item: autoscroll_bounds.origin.y - item_origin.y,
634 });
635 }
636 }
637
638 item_origin.y += item.size.height;
639 }
640 } else {
641 layout_response.item_layouts.clear();
642 }
643
644 Ok(layout_response)
645 })
646 }
647}
648
649impl std::fmt::Debug for ListItem {
650 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
651 match self {
652 Self::Unmeasured { .. } => write!(f, "Unrendered"),
653 Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
654 }
655 }
656}
657
658/// An offset into the list's items, in terms of the item index and the number
659/// of pixels off the top left of the item.
660#[derive(Debug, Clone, Copy, Default)]
661pub struct ListOffset {
662 /// The index of an item in the list
663 pub item_ix: usize,
664 /// The number of pixels to offset from the item index.
665 pub offset_in_item: Pixels,
666}
667
668impl Element for List {
669 type RequestLayoutState = ();
670 type PrepaintState = ListPrepaintState;
671
672 fn request_layout(
673 &mut self,
674 cx: &mut crate::ElementContext,
675 ) -> (crate::LayoutId, Self::RequestLayoutState) {
676 let layout_id = match self.sizing_behavior {
677 ListSizingBehavior::Infer => {
678 let mut style = Style::default();
679 style.overflow.y = Overflow::Scroll;
680 style.refine(&self.style);
681 cx.with_text_style(style.text_style().cloned(), |cx| {
682 let state = &mut *self.state.0.borrow_mut();
683
684 let available_height = if let Some(last_bounds) = state.last_layout_bounds {
685 last_bounds.size.height
686 } else {
687 // If we don't have the last layout bounds (first render),
688 // we might just use the overdraw value as the available height to layout enough items.
689 state.overdraw
690 };
691 let padding = style.padding.to_pixels(
692 state.last_layout_bounds.unwrap_or_default().size.into(),
693 cx.rem_size(),
694 );
695
696 let layout_response = state.layout_items(None, available_height, &padding, cx);
697 let max_element_width = layout_response.max_item_width;
698
699 let summary = state.items.summary();
700 let total_height = summary.height;
701
702 cx.request_measured_layout(
703 style,
704 move |known_dimensions, available_space, _cx| {
705 let width =
706 known_dimensions
707 .width
708 .unwrap_or(match available_space.width {
709 AvailableSpace::Definite(x) => x,
710 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
711 max_element_width
712 }
713 });
714 let height = match available_space.height {
715 AvailableSpace::Definite(height) => total_height.min(height),
716 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
717 total_height
718 }
719 };
720 size(width, height)
721 },
722 )
723 })
724 }
725 ListSizingBehavior::Auto => {
726 let mut style = Style::default();
727 style.refine(&self.style);
728 cx.with_text_style(style.text_style().cloned(), |cx| {
729 cx.request_layout(&style, None)
730 })
731 }
732 };
733 (layout_id, ())
734 }
735
736 fn prepaint(
737 &mut self,
738 bounds: Bounds<Pixels>,
739 _: &mut Self::RequestLayoutState,
740 cx: &mut ElementContext,
741 ) -> ListPrepaintState {
742 let state = &mut *self.state.0.borrow_mut();
743 state.reset = false;
744
745 let mut style = Style::default();
746 style.refine(&self.style);
747
748 let hitbox = cx.insert_hitbox(bounds, false);
749
750 // If the width of the list has changed, invalidate all cached item heights
751 if state.last_layout_bounds.map_or(true, |last_bounds| {
752 last_bounds.size.width != bounds.size.width
753 }) {
754 let new_items = SumTree::from_iter(
755 state.items.iter().map(|item| ListItem::Unmeasured {
756 focus_handle: item.focus_handle(),
757 }),
758 &(),
759 );
760
761 state.items = new_items;
762 }
763
764 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
765 let layout = match state.prepaint_items(bounds, padding, cx) {
766 Ok(layout) => layout,
767 Err(autoscroll_request) => {
768 state.logical_scroll_top = Some(autoscroll_request);
769 state.prepaint_items(bounds, padding, cx).unwrap()
770 }
771 };
772
773 state.last_layout_bounds = Some(bounds);
774 state.last_padding = Some(padding);
775 ListPrepaintState { hitbox, layout }
776 }
777
778 fn paint(
779 &mut self,
780 bounds: Bounds<crate::Pixels>,
781 _: &mut Self::RequestLayoutState,
782 prepaint: &mut Self::PrepaintState,
783 cx: &mut crate::ElementContext,
784 ) {
785 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
786 for item in &mut prepaint.layout.item_layouts {
787 item.element.paint(cx);
788 }
789 });
790
791 let list_state = self.state.clone();
792 let height = bounds.size.height;
793 let scroll_top = prepaint.layout.scroll_top;
794 let hitbox_id = prepaint.hitbox.id;
795 cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
796 if phase == DispatchPhase::Bubble && hitbox_id.is_hovered(cx) {
797 list_state.0.borrow_mut().scroll(
798 &scroll_top,
799 height,
800 event.delta.pixel_delta(px(20.)),
801 cx,
802 )
803 }
804 });
805 }
806}
807
808impl IntoElement for List {
809 type Element = Self;
810
811 fn into_element(self) -> Self::Element {
812 self
813 }
814}
815
816impl Styled for List {
817 fn style(&mut self) -> &mut StyleRefinement {
818 &mut self.style
819 }
820}
821
822impl sum_tree::Item for ListItem {
823 type Summary = ListItemSummary;
824
825 fn summary(&self) -> Self::Summary {
826 match self {
827 ListItem::Unmeasured { focus_handle } => ListItemSummary {
828 count: 1,
829 rendered_count: 0,
830 unrendered_count: 1,
831 height: px(0.),
832 has_focus_handles: focus_handle.is_some(),
833 },
834 ListItem::Measured {
835 size, focus_handle, ..
836 } => ListItemSummary {
837 count: 1,
838 rendered_count: 1,
839 unrendered_count: 0,
840 height: size.height,
841 has_focus_handles: focus_handle.is_some(),
842 },
843 }
844 }
845}
846
847impl sum_tree::Summary for ListItemSummary {
848 type Context = ();
849
850 fn add_summary(&mut self, summary: &Self, _: &()) {
851 self.count += summary.count;
852 self.rendered_count += summary.rendered_count;
853 self.unrendered_count += summary.unrendered_count;
854 self.height += summary.height;
855 self.has_focus_handles |= summary.has_focus_handles;
856 }
857}
858
859impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
860 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
861 self.0 += summary.count;
862 }
863}
864
865impl<'a> sum_tree::Dimension<'a, ListItemSummary> for RenderedCount {
866 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
867 self.0 += summary.rendered_count;
868 }
869}
870
871impl<'a> sum_tree::Dimension<'a, ListItemSummary> for UnrenderedCount {
872 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
873 self.0 += summary.unrendered_count;
874 }
875}
876
877impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
878 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
879 self.0 += summary.height;
880 }
881}
882
883impl<'a> sum_tree::SeekTarget<'a, ListItemSummary, ListItemSummary> for Count {
884 fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
885 self.0.partial_cmp(&other.count).unwrap()
886 }
887}
888
889impl<'a> sum_tree::SeekTarget<'a, ListItemSummary, ListItemSummary> for Height {
890 fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
891 self.0.partial_cmp(&other.height).unwrap()
892 }
893}
894
895#[cfg(test)]
896mod test {
897
898 use gpui::{ScrollDelta, ScrollWheelEvent};
899
900 use crate::{self as gpui, TestAppContext};
901
902 #[gpui::test]
903 fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
904 use crate::{div, list, point, px, size, Element, ListState, Styled};
905
906 let cx = cx.add_empty_window();
907
908 let state = ListState::new(5, crate::ListAlignment::Top, px(10.), |_, _| {
909 div().h(px(10.)).w_full().into_any()
910 });
911
912 // Ensure that the list is scrolled to the top
913 state.scroll_to(gpui::ListOffset {
914 item_ix: 0,
915 offset_in_item: px(0.0),
916 });
917
918 // Paint
919 cx.draw(
920 point(px(0.), px(0.)),
921 size(px(100.), px(20.)).into(),
922 |_| list(state.clone()).w_full().h_full().into_any(),
923 );
924
925 // Reset
926 state.reset(5);
927
928 // And then receive a scroll event _before_ the next paint
929 cx.simulate_event(ScrollWheelEvent {
930 position: point(px(1.), px(1.)),
931 delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
932 ..Default::default()
933 });
934
935 // Scroll position should stay at the top of the list
936 assert_eq!(state.logical_scroll_top().item_ix, 0);
937 assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
938 }
939}