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 {
206 let state = &mut *self.0.borrow_mut();
207 state.reset = true;
208 state.logical_scroll_top = None;
209 }
210
211 self.splice(0..element_count, element_count);
212 }
213
214 /// The number of items in this list.
215 pub fn item_count(&self) -> usize {
216 self.0.borrow().items.summary().count
217 }
218
219 /// Inform the list state that the items in `old_range` have been replaced
220 /// by `count` new items that must be recalculated.
221 pub fn splice(&self, old_range: Range<usize>, count: usize) {
222 self.splice_focusable(old_range, (0..count).map(|_| None))
223 }
224
225 /// Register with the list state that the items in `old_range` have been replaced
226 /// by new items. As opposed to [`splice`], this method allows an iterator of optional focus handles
227 /// to be supplied to properly integrate with items in the list that can be focused. If a focused item
228 /// is scrolled out of view, the list will continue to render it to allow keyboard interaction.
229 pub fn splice_focusable(
230 &self,
231 old_range: Range<usize>,
232 focus_handles: impl IntoIterator<Item = Option<FocusHandle>>,
233 ) {
234 let state = &mut *self.0.borrow_mut();
235
236 let mut old_items = state.items.cursor::<Count>();
237 let mut new_items = old_items.slice(&Count(old_range.start), Bias::Right, &());
238 old_items.seek_forward(&Count(old_range.end), Bias::Right, &());
239
240 let mut spliced_count = 0;
241 new_items.extend(
242 focus_handles.into_iter().map(|focus_handle| {
243 spliced_count += 1;
244 ListItem::Unmeasured { focus_handle }
245 }),
246 &(),
247 );
248 new_items.append(old_items.suffix(&()), &());
249 drop(old_items);
250 state.items = new_items;
251
252 if let Some(ListOffset {
253 item_ix,
254 offset_in_item,
255 }) = state.logical_scroll_top.as_mut()
256 {
257 if old_range.contains(item_ix) {
258 *item_ix = old_range.start;
259 *offset_in_item = px(0.);
260 } else if old_range.end <= *item_ix {
261 *item_ix = *item_ix - (old_range.end - old_range.start) + spliced_count;
262 }
263 }
264 }
265
266 /// Set a handler that will be called when the list is scrolled.
267 pub fn set_scroll_handler(
268 &self,
269 handler: impl FnMut(&ListScrollEvent, &mut WindowContext) + 'static,
270 ) {
271 self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
272 }
273
274 /// Get the current scroll offset, in terms of the list's items.
275 pub fn logical_scroll_top(&self) -> ListOffset {
276 self.0.borrow().logical_scroll_top()
277 }
278
279 /// Scroll the list to the given offset
280 pub fn scroll_to(&self, mut scroll_top: ListOffset) {
281 let state = &mut *self.0.borrow_mut();
282 let item_count = state.items.summary().count;
283 if scroll_top.item_ix >= item_count {
284 scroll_top.item_ix = item_count;
285 scroll_top.offset_in_item = px(0.);
286 }
287
288 state.logical_scroll_top = Some(scroll_top);
289 }
290
291 /// Scroll the list to the given item, such that the item is fully visible.
292 pub fn scroll_to_reveal_item(&self, ix: usize) {
293 let state = &mut *self.0.borrow_mut();
294
295 let mut scroll_top = state.logical_scroll_top();
296 let height = state
297 .last_layout_bounds
298 .map_or(px(0.), |bounds| bounds.size.height);
299 let padding = state.last_padding.unwrap_or_default();
300
301 if ix <= scroll_top.item_ix {
302 scroll_top.item_ix = ix;
303 scroll_top.offset_in_item = px(0.);
304 } else {
305 let mut cursor = state.items.cursor::<ListItemSummary>();
306 cursor.seek(&Count(ix + 1), Bias::Right, &());
307 let bottom = cursor.start().height + padding.top;
308 let goal_top = px(0.).max(bottom - height + padding.bottom);
309
310 cursor.seek(&Height(goal_top), Bias::Left, &());
311 let start_ix = cursor.start().count;
312 let start_item_top = cursor.start().height;
313
314 if start_ix >= scroll_top.item_ix {
315 scroll_top.item_ix = start_ix;
316 scroll_top.offset_in_item = goal_top - start_item_top;
317 }
318 }
319
320 state.logical_scroll_top = Some(scroll_top);
321 }
322
323 /// Get the bounds for the given item in window coordinates, if it's
324 /// been rendered.
325 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
326 let state = &*self.0.borrow();
327
328 let bounds = state.last_layout_bounds.unwrap_or_default();
329 let scroll_top = state.logical_scroll_top();
330 if ix < scroll_top.item_ix {
331 return None;
332 }
333
334 let mut cursor = state.items.cursor::<(Count, Height)>();
335 cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
336
337 let scroll_top = cursor.start().1 .0 + scroll_top.offset_in_item;
338
339 cursor.seek_forward(&Count(ix), Bias::Right, &());
340 if let Some(&ListItem::Measured { size, .. }) = cursor.item() {
341 let &(Count(count), Height(top)) = cursor.start();
342 if count == ix {
343 let top = bounds.top() + top - scroll_top;
344 return Some(Bounds::from_corners(
345 point(bounds.left(), top),
346 point(bounds.right(), top + size.height),
347 ));
348 }
349 }
350 None
351 }
352}
353
354impl StateInner {
355 fn visible_range(&self, height: Pixels, scroll_top: &ListOffset) -> Range<usize> {
356 let mut cursor = self.items.cursor::<ListItemSummary>();
357 cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
358 let start_y = cursor.start().height + scroll_top.offset_in_item;
359 cursor.seek_forward(&Height(start_y + height), Bias::Left, &());
360 scroll_top.item_ix..cursor.start().count + 1
361 }
362
363 fn scroll(
364 &mut self,
365 scroll_top: &ListOffset,
366 height: Pixels,
367 delta: Point<Pixels>,
368 cx: &mut WindowContext,
369 ) {
370 // Drop scroll events after a reset, since we can't calculate
371 // the new logical scroll top without the item heights
372 if self.reset {
373 return;
374 }
375
376 let padding = self.last_padding.unwrap_or_default();
377 let scroll_max =
378 (self.items.summary().height + padding.top + padding.bottom - height).max(px(0.));
379 let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
380 .max(px(0.))
381 .min(scroll_max);
382
383 if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
384 self.logical_scroll_top = None;
385 } else {
386 let mut cursor = self.items.cursor::<ListItemSummary>();
387 cursor.seek(&Height(new_scroll_top), Bias::Right, &());
388 let item_ix = cursor.start().count;
389 let offset_in_item = new_scroll_top - cursor.start().height;
390 self.logical_scroll_top = Some(ListOffset {
391 item_ix,
392 offset_in_item,
393 });
394 }
395
396 if self.scroll_handler.is_some() {
397 let visible_range = self.visible_range(height, scroll_top);
398 self.scroll_handler.as_mut().unwrap()(
399 &ListScrollEvent {
400 visible_range,
401 count: self.items.summary().count,
402 is_scrolled: self.logical_scroll_top.is_some(),
403 },
404 cx,
405 );
406 }
407
408 cx.refresh();
409 }
410
411 fn logical_scroll_top(&self) -> ListOffset {
412 self.logical_scroll_top
413 .unwrap_or_else(|| match self.alignment {
414 ListAlignment::Top => ListOffset {
415 item_ix: 0,
416 offset_in_item: px(0.),
417 },
418 ListAlignment::Bottom => ListOffset {
419 item_ix: self.items.summary().count,
420 offset_in_item: px(0.),
421 },
422 })
423 }
424
425 fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
426 let mut cursor = self.items.cursor::<ListItemSummary>();
427 cursor.seek(&Count(logical_scroll_top.item_ix), Bias::Right, &());
428 cursor.start().height + logical_scroll_top.offset_in_item
429 }
430
431 fn layout_items(
432 &mut self,
433 available_width: Option<Pixels>,
434 available_height: Pixels,
435 padding: &Edges<Pixels>,
436 cx: &mut ElementContext,
437 ) -> LayoutItemsResponse {
438 let old_items = self.items.clone();
439 let mut measured_items = VecDeque::new();
440 let mut item_layouts = VecDeque::new();
441 let mut rendered_height = padding.top;
442 let mut max_item_width = px(0.);
443 let mut scroll_top = self.logical_scroll_top();
444 let mut rendered_focused_item = false;
445
446 let available_item_space = size(
447 available_width.map_or(AvailableSpace::MinContent, |width| {
448 AvailableSpace::Definite(width)
449 }),
450 AvailableSpace::MinContent,
451 );
452
453 let mut cursor = old_items.cursor::<Count>();
454
455 // Render items after the scroll top, including those in the trailing overdraw
456 cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
457 for (ix, item) in cursor.by_ref().enumerate() {
458 let visible_height = rendered_height - scroll_top.offset_in_item;
459 if visible_height >= available_height + self.overdraw {
460 break;
461 }
462
463 // Use the previously cached height and focus handle if available
464 let mut size = item.size();
465
466 // If we're within the visible area or the height wasn't cached, render and measure the item's element
467 if visible_height < available_height || size.is_none() {
468 let item_index = scroll_top.item_ix + ix;
469 let mut element = (self.render_item)(item_index, cx);
470 let element_size = element.layout_as_root(available_item_space, cx);
471 size = Some(element_size);
472 if visible_height < available_height {
473 item_layouts.push_back(ItemLayout {
474 index: item_index,
475 element,
476 size: element_size,
477 });
478 if item.contains_focused(cx) {
479 rendered_focused_item = true;
480 }
481 }
482 }
483
484 let size = size.unwrap();
485 rendered_height += size.height;
486 max_item_width = max_item_width.max(size.width);
487 measured_items.push_back(ListItem::Measured {
488 size,
489 focus_handle: item.focus_handle(),
490 });
491 }
492 rendered_height += padding.bottom;
493
494 // Prepare to start walking upward from the item at the scroll top.
495 cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
496
497 // If the rendered items do not fill the visible region, then adjust
498 // the scroll top upward.
499 if rendered_height - scroll_top.offset_in_item < available_height {
500 while rendered_height < available_height {
501 cursor.prev(&());
502 if let Some(item) = cursor.item() {
503 let item_index = cursor.start().0;
504 let mut element = (self.render_item)(item_index, cx);
505 let element_size = element.layout_as_root(available_item_space, cx);
506 let focus_handle = item.focus_handle();
507 rendered_height += element_size.height;
508 measured_items.push_front(ListItem::Measured {
509 size: element_size,
510 focus_handle,
511 });
512 item_layouts.push_front(ItemLayout {
513 index: item_index,
514 element,
515 size: element_size,
516 });
517 if item.contains_focused(cx) {
518 rendered_focused_item = true;
519 }
520 } else {
521 break;
522 }
523 }
524
525 scroll_top = ListOffset {
526 item_ix: cursor.start().0,
527 offset_in_item: rendered_height - available_height,
528 };
529
530 match self.alignment {
531 ListAlignment::Top => {
532 scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
533 self.logical_scroll_top = Some(scroll_top);
534 }
535 ListAlignment::Bottom => {
536 scroll_top = ListOffset {
537 item_ix: cursor.start().0,
538 offset_in_item: rendered_height - available_height,
539 };
540 self.logical_scroll_top = None;
541 }
542 };
543 }
544
545 // Measure items in the leading overdraw
546 let mut leading_overdraw = scroll_top.offset_in_item;
547 while leading_overdraw < self.overdraw {
548 cursor.prev(&());
549 if let Some(item) = cursor.item() {
550 let size = if let ListItem::Measured { size, .. } = item {
551 *size
552 } else {
553 let mut element = (self.render_item)(cursor.start().0, cx);
554 element.layout_as_root(available_item_space, cx)
555 };
556
557 leading_overdraw += size.height;
558 measured_items.push_front(ListItem::Measured {
559 size,
560 focus_handle: item.focus_handle(),
561 });
562 } else {
563 break;
564 }
565 }
566
567 let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
568 let mut cursor = old_items.cursor::<Count>();
569 let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right, &());
570 new_items.extend(measured_items, &());
571 cursor.seek(&Count(measured_range.end), Bias::Right, &());
572 new_items.append(cursor.suffix(&()), &());
573 self.items = new_items;
574
575 // If none of the visible items are focused, check if an off-screen item is focused
576 // and include it to be rendered after the visible items so keyboard interaction continues
577 // to work for it.
578 if !rendered_focused_item {
579 let mut cursor = self
580 .items
581 .filter::<_, Count>(|summary| summary.has_focus_handles);
582 cursor.next(&());
583 while let Some(item) = cursor.item() {
584 if item.contains_focused(cx) {
585 let item_index = cursor.start().0;
586 let mut element = (self.render_item)(cursor.start().0, cx);
587 let size = element.layout_as_root(available_item_space, cx);
588 item_layouts.push_back(ItemLayout {
589 index: item_index,
590 element,
591 size,
592 });
593 break;
594 }
595 cursor.next(&());
596 }
597 }
598
599 LayoutItemsResponse {
600 max_item_width,
601 scroll_top,
602 item_layouts,
603 }
604 }
605
606 fn prepaint_items(
607 &mut self,
608 bounds: Bounds<Pixels>,
609 padding: Edges<Pixels>,
610 cx: &mut ElementContext,
611 ) -> Result<LayoutItemsResponse, ListOffset> {
612 cx.transact(|cx| {
613 let mut layout_response =
614 self.layout_items(Some(bounds.size.width), bounds.size.height, &padding, cx);
615
616 // Only paint the visible items, if there is actually any space for them (taking padding into account)
617 if bounds.size.height > padding.top + padding.bottom {
618 let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
619 item_origin.y -= layout_response.scroll_top.offset_in_item;
620 for item in &mut layout_response.item_layouts {
621 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
622 item.element.prepaint_at(item_origin, cx);
623 });
624
625 if let Some(autoscroll_bounds) = cx.take_autoscroll() {
626 if bounds.intersect(&autoscroll_bounds) != autoscroll_bounds {
627 return Err(ListOffset {
628 item_ix: item.index,
629 offset_in_item: autoscroll_bounds.origin.y - item_origin.y,
630 });
631 }
632 }
633
634 item_origin.y += item.size.height;
635 }
636 } else {
637 layout_response.item_layouts.clear();
638 }
639
640 Ok(layout_response)
641 })
642 }
643}
644
645impl std::fmt::Debug for ListItem {
646 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
647 match self {
648 Self::Unmeasured { .. } => write!(f, "Unrendered"),
649 Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
650 }
651 }
652}
653
654/// An offset into the list's items, in terms of the item index and the number
655/// of pixels off the top left of the item.
656#[derive(Debug, Clone, Copy, Default)]
657pub struct ListOffset {
658 /// The index of an item in the list
659 pub item_ix: usize,
660 /// The number of pixels to offset from the item index.
661 pub offset_in_item: Pixels,
662}
663
664impl Element for List {
665 type RequestLayoutState = ();
666 type PrepaintState = ListPrepaintState;
667
668 fn request_layout(
669 &mut self,
670 cx: &mut crate::ElementContext,
671 ) -> (crate::LayoutId, Self::RequestLayoutState) {
672 let layout_id = match self.sizing_behavior {
673 ListSizingBehavior::Infer => {
674 let mut style = Style::default();
675 style.overflow.y = Overflow::Scroll;
676 style.refine(&self.style);
677 cx.with_text_style(style.text_style().cloned(), |cx| {
678 let state = &mut *self.state.0.borrow_mut();
679
680 let available_height = if let Some(last_bounds) = state.last_layout_bounds {
681 last_bounds.size.height
682 } else {
683 // If we don't have the last layout bounds (first render),
684 // we might just use the overdraw value as the available height to layout enough items.
685 state.overdraw
686 };
687 let padding = style.padding.to_pixels(
688 state.last_layout_bounds.unwrap_or_default().size.into(),
689 cx.rem_size(),
690 );
691
692 let layout_response = state.layout_items(None, available_height, &padding, cx);
693 let max_element_width = layout_response.max_item_width;
694
695 let summary = state.items.summary();
696 let total_height = summary.height;
697
698 cx.request_measured_layout(
699 style,
700 move |known_dimensions, available_space, _cx| {
701 let width =
702 known_dimensions
703 .width
704 .unwrap_or(match available_space.width {
705 AvailableSpace::Definite(x) => x,
706 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
707 max_element_width
708 }
709 });
710 let height = match available_space.height {
711 AvailableSpace::Definite(height) => total_height.min(height),
712 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
713 total_height
714 }
715 };
716 size(width, height)
717 },
718 )
719 })
720 }
721 ListSizingBehavior::Auto => {
722 let mut style = Style::default();
723 style.refine(&self.style);
724 cx.with_text_style(style.text_style().cloned(), |cx| {
725 cx.request_layout(&style, None)
726 })
727 }
728 };
729 (layout_id, ())
730 }
731
732 fn prepaint(
733 &mut self,
734 bounds: Bounds<Pixels>,
735 _: &mut Self::RequestLayoutState,
736 cx: &mut ElementContext,
737 ) -> ListPrepaintState {
738 let state = &mut *self.state.0.borrow_mut();
739 state.reset = false;
740
741 let mut style = Style::default();
742 style.refine(&self.style);
743
744 let hitbox = cx.insert_hitbox(bounds, false);
745
746 // If the width of the list has changed, invalidate all cached item heights
747 if state.last_layout_bounds.map_or(true, |last_bounds| {
748 last_bounds.size.width != bounds.size.width
749 }) {
750 let new_items = SumTree::from_iter(
751 state.items.iter().map(|item| ListItem::Unmeasured {
752 focus_handle: item.focus_handle(),
753 }),
754 &(),
755 );
756
757 state.items = new_items;
758 }
759
760 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
761 let layout = match state.prepaint_items(bounds, padding, cx) {
762 Ok(layout) => layout,
763 Err(autoscroll_request) => {
764 state.logical_scroll_top = Some(autoscroll_request);
765 state.prepaint_items(bounds, padding, cx).unwrap()
766 }
767 };
768
769 state.last_layout_bounds = Some(bounds);
770 state.last_padding = Some(padding);
771 ListPrepaintState { hitbox, layout }
772 }
773
774 fn paint(
775 &mut self,
776 bounds: Bounds<crate::Pixels>,
777 _: &mut Self::RequestLayoutState,
778 prepaint: &mut Self::PrepaintState,
779 cx: &mut crate::ElementContext,
780 ) {
781 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
782 for item in &mut prepaint.layout.item_layouts {
783 item.element.paint(cx);
784 }
785 });
786
787 let list_state = self.state.clone();
788 let height = bounds.size.height;
789 let scroll_top = prepaint.layout.scroll_top;
790 let hitbox_id = prepaint.hitbox.id;
791 cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
792 if phase == DispatchPhase::Bubble && hitbox_id.is_hovered(cx) {
793 list_state.0.borrow_mut().scroll(
794 &scroll_top,
795 height,
796 event.delta.pixel_delta(px(20.)),
797 cx,
798 )
799 }
800 });
801 }
802}
803
804impl IntoElement for List {
805 type Element = Self;
806
807 fn into_element(self) -> Self::Element {
808 self
809 }
810}
811
812impl Styled for List {
813 fn style(&mut self) -> &mut StyleRefinement {
814 &mut self.style
815 }
816}
817
818impl sum_tree::Item for ListItem {
819 type Summary = ListItemSummary;
820
821 fn summary(&self) -> Self::Summary {
822 match self {
823 ListItem::Unmeasured { focus_handle } => ListItemSummary {
824 count: 1,
825 rendered_count: 0,
826 unrendered_count: 1,
827 height: px(0.),
828 has_focus_handles: focus_handle.is_some(),
829 },
830 ListItem::Measured {
831 size, focus_handle, ..
832 } => ListItemSummary {
833 count: 1,
834 rendered_count: 1,
835 unrendered_count: 0,
836 height: size.height,
837 has_focus_handles: focus_handle.is_some(),
838 },
839 }
840 }
841}
842
843impl sum_tree::Summary for ListItemSummary {
844 type Context = ();
845
846 fn add_summary(&mut self, summary: &Self, _: &()) {
847 self.count += summary.count;
848 self.rendered_count += summary.rendered_count;
849 self.unrendered_count += summary.unrendered_count;
850 self.height += summary.height;
851 self.has_focus_handles |= summary.has_focus_handles;
852 }
853}
854
855impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
856 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
857 self.0 += summary.count;
858 }
859}
860
861impl<'a> sum_tree::Dimension<'a, ListItemSummary> for RenderedCount {
862 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
863 self.0 += summary.rendered_count;
864 }
865}
866
867impl<'a> sum_tree::Dimension<'a, ListItemSummary> for UnrenderedCount {
868 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
869 self.0 += summary.unrendered_count;
870 }
871}
872
873impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
874 fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
875 self.0 += summary.height;
876 }
877}
878
879impl<'a> sum_tree::SeekTarget<'a, ListItemSummary, ListItemSummary> for Count {
880 fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
881 self.0.partial_cmp(&other.count).unwrap()
882 }
883}
884
885impl<'a> sum_tree::SeekTarget<'a, ListItemSummary, ListItemSummary> for Height {
886 fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
887 self.0.partial_cmp(&other.height).unwrap()
888 }
889}
890
891#[cfg(test)]
892mod test {
893
894 use gpui::{ScrollDelta, ScrollWheelEvent};
895
896 use crate::{self as gpui, TestAppContext};
897
898 #[gpui::test]
899 fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
900 use crate::{div, list, point, px, size, Element, ListState, Styled};
901
902 let cx = cx.add_empty_window();
903
904 let state = ListState::new(5, crate::ListAlignment::Top, px(10.), |_, _| {
905 div().h(px(10.)).w_full().into_any()
906 });
907
908 // Ensure that the list is scrolled to the top
909 state.scroll_to(gpui::ListOffset {
910 item_ix: 0,
911 offset_in_item: px(0.0),
912 });
913
914 // Paint
915 cx.draw(
916 point(px(0.), px(0.)),
917 size(px(100.), px(20.)).into(),
918 |_| list(state.clone()).w_full().h_full().into_any(),
919 );
920
921 // Reset
922 state.reset(5);
923
924 // And then receive a scroll event _before_ the next paint
925 cx.simulate_event(ScrollWheelEvent {
926 position: point(px(1.), px(1.)),
927 delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
928 ..Default::default()
929 });
930
931 // Scroll position should stay at the top of the list
932 assert_eq!(state.logical_scroll_top().item_ix, 0);
933 assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
934 }
935}