list.rs

  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        autoscroll: bool,
612        cx: &mut ElementContext,
613    ) -> Result<LayoutItemsResponse, ListOffset> {
614        cx.transact(|cx| {
615            let mut layout_response =
616                self.layout_items(Some(bounds.size.width), bounds.size.height, &padding, cx);
617
618            // Avoid honoring autoscroll requests from elements other than our children.
619            cx.take_autoscroll();
620
621            // Only paint the visible items, if there is actually any space for them (taking padding into account)
622            if bounds.size.height > padding.top + padding.bottom {
623                let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
624                item_origin.y -= layout_response.scroll_top.offset_in_item;
625                for item in &mut layout_response.item_layouts {
626                    cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
627                        item.element.prepaint_at(item_origin, cx);
628                    });
629
630                    if let Some(autoscroll_bounds) = cx.take_autoscroll() {
631                        if autoscroll {
632                            if autoscroll_bounds.top() < bounds.top() {
633                                return Err(ListOffset {
634                                    item_ix: item.index,
635                                    offset_in_item: autoscroll_bounds.top() - item_origin.y,
636                                });
637                            } else if autoscroll_bounds.bottom() > bounds.bottom() {
638                                let mut cursor = self.items.cursor::<Count>();
639                                cursor.seek(&Count(item.index), Bias::Right, &());
640                                let mut height = bounds.size.height - padding.top - padding.bottom;
641
642                                // Account for the height of the element down until the autoscroll bottom.
643                                height -= autoscroll_bounds.bottom() - item_origin.y;
644
645                                // Keep decreasing the scroll top until we fill all the available space.
646                                while height > Pixels::ZERO {
647                                    cursor.prev(&());
648                                    let Some(item) = cursor.item() else { break };
649
650                                    let size = item.size().unwrap_or_else(|| {
651                                        let mut item = (self.render_item)(cursor.start().0, cx);
652                                        let item_available_size = size(
653                                            bounds.size.width.into(),
654                                            AvailableSpace::MinContent,
655                                        );
656                                        item.layout_as_root(item_available_size, cx)
657                                    });
658                                    height -= size.height;
659                                }
660
661                                return Err(ListOffset {
662                                    item_ix: cursor.start().0,
663                                    offset_in_item: if height < Pixels::ZERO {
664                                        -height
665                                    } else {
666                                        Pixels::ZERO
667                                    },
668                                });
669                            }
670                        }
671                    }
672
673                    item_origin.y += item.size.height;
674                }
675            } else {
676                layout_response.item_layouts.clear();
677            }
678
679            Ok(layout_response)
680        })
681    }
682}
683
684impl std::fmt::Debug for ListItem {
685    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
686        match self {
687            Self::Unmeasured { .. } => write!(f, "Unrendered"),
688            Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
689        }
690    }
691}
692
693/// An offset into the list's items, in terms of the item index and the number
694/// of pixels off the top left of the item.
695#[derive(Debug, Clone, Copy, Default)]
696pub struct ListOffset {
697    /// The index of an item in the list
698    pub item_ix: usize,
699    /// The number of pixels to offset from the item index.
700    pub offset_in_item: Pixels,
701}
702
703impl Element for List {
704    type RequestLayoutState = ();
705    type PrepaintState = ListPrepaintState;
706
707    fn request_layout(
708        &mut self,
709        cx: &mut crate::ElementContext,
710    ) -> (crate::LayoutId, Self::RequestLayoutState) {
711        let layout_id = match self.sizing_behavior {
712            ListSizingBehavior::Infer => {
713                let mut style = Style::default();
714                style.overflow.y = Overflow::Scroll;
715                style.refine(&self.style);
716                cx.with_text_style(style.text_style().cloned(), |cx| {
717                    let state = &mut *self.state.0.borrow_mut();
718
719                    let available_height = if let Some(last_bounds) = state.last_layout_bounds {
720                        last_bounds.size.height
721                    } else {
722                        // If we don't have the last layout bounds (first render),
723                        // we might just use the overdraw value as the available height to layout enough items.
724                        state.overdraw
725                    };
726                    let padding = style.padding.to_pixels(
727                        state.last_layout_bounds.unwrap_or_default().size.into(),
728                        cx.rem_size(),
729                    );
730
731                    let layout_response = state.layout_items(None, available_height, &padding, cx);
732                    let max_element_width = layout_response.max_item_width;
733
734                    let summary = state.items.summary();
735                    let total_height = summary.height;
736
737                    cx.request_measured_layout(
738                        style,
739                        move |known_dimensions, available_space, _cx| {
740                            let width =
741                                known_dimensions
742                                    .width
743                                    .unwrap_or(match available_space.width {
744                                        AvailableSpace::Definite(x) => x,
745                                        AvailableSpace::MinContent | AvailableSpace::MaxContent => {
746                                            max_element_width
747                                        }
748                                    });
749                            let height = match available_space.height {
750                                AvailableSpace::Definite(height) => total_height.min(height),
751                                AvailableSpace::MinContent | AvailableSpace::MaxContent => {
752                                    total_height
753                                }
754                            };
755                            size(width, height)
756                        },
757                    )
758                })
759            }
760            ListSizingBehavior::Auto => {
761                let mut style = Style::default();
762                style.refine(&self.style);
763                cx.with_text_style(style.text_style().cloned(), |cx| {
764                    cx.request_layout(&style, None)
765                })
766            }
767        };
768        (layout_id, ())
769    }
770
771    fn prepaint(
772        &mut self,
773        bounds: Bounds<Pixels>,
774        _: &mut Self::RequestLayoutState,
775        cx: &mut ElementContext,
776    ) -> ListPrepaintState {
777        let state = &mut *self.state.0.borrow_mut();
778        state.reset = false;
779
780        let mut style = Style::default();
781        style.refine(&self.style);
782
783        let hitbox = cx.insert_hitbox(bounds, false);
784
785        // If the width of the list has changed, invalidate all cached item heights
786        if state.last_layout_bounds.map_or(true, |last_bounds| {
787            last_bounds.size.width != bounds.size.width
788        }) {
789            let new_items = SumTree::from_iter(
790                state.items.iter().map(|item| ListItem::Unmeasured {
791                    focus_handle: item.focus_handle(),
792                }),
793                &(),
794            );
795
796            state.items = new_items;
797        }
798
799        let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
800        let layout = match state.prepaint_items(bounds, padding, true, cx) {
801            Ok(layout) => layout,
802            Err(autoscroll_request) => {
803                state.logical_scroll_top = Some(autoscroll_request);
804                state.prepaint_items(bounds, padding, false, cx).unwrap()
805            }
806        };
807
808        state.last_layout_bounds = Some(bounds);
809        state.last_padding = Some(padding);
810        ListPrepaintState { hitbox, layout }
811    }
812
813    fn paint(
814        &mut self,
815        bounds: Bounds<crate::Pixels>,
816        _: &mut Self::RequestLayoutState,
817        prepaint: &mut Self::PrepaintState,
818        cx: &mut crate::ElementContext,
819    ) {
820        cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
821            for item in &mut prepaint.layout.item_layouts {
822                item.element.paint(cx);
823            }
824        });
825
826        let list_state = self.state.clone();
827        let height = bounds.size.height;
828        let scroll_top = prepaint.layout.scroll_top;
829        let hitbox_id = prepaint.hitbox.id;
830        cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
831            if phase == DispatchPhase::Bubble && hitbox_id.is_hovered(cx) {
832                list_state.0.borrow_mut().scroll(
833                    &scroll_top,
834                    height,
835                    event.delta.pixel_delta(px(20.)),
836                    cx,
837                )
838            }
839        });
840    }
841}
842
843impl IntoElement for List {
844    type Element = Self;
845
846    fn into_element(self) -> Self::Element {
847        self
848    }
849}
850
851impl Styled for List {
852    fn style(&mut self) -> &mut StyleRefinement {
853        &mut self.style
854    }
855}
856
857impl sum_tree::Item for ListItem {
858    type Summary = ListItemSummary;
859
860    fn summary(&self) -> Self::Summary {
861        match self {
862            ListItem::Unmeasured { focus_handle } => ListItemSummary {
863                count: 1,
864                rendered_count: 0,
865                unrendered_count: 1,
866                height: px(0.),
867                has_focus_handles: focus_handle.is_some(),
868            },
869            ListItem::Measured {
870                size, focus_handle, ..
871            } => ListItemSummary {
872                count: 1,
873                rendered_count: 1,
874                unrendered_count: 0,
875                height: size.height,
876                has_focus_handles: focus_handle.is_some(),
877            },
878        }
879    }
880}
881
882impl sum_tree::Summary for ListItemSummary {
883    type Context = ();
884
885    fn add_summary(&mut self, summary: &Self, _: &()) {
886        self.count += summary.count;
887        self.rendered_count += summary.rendered_count;
888        self.unrendered_count += summary.unrendered_count;
889        self.height += summary.height;
890        self.has_focus_handles |= summary.has_focus_handles;
891    }
892}
893
894impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
895    fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
896        self.0 += summary.count;
897    }
898}
899
900impl<'a> sum_tree::Dimension<'a, ListItemSummary> for RenderedCount {
901    fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
902        self.0 += summary.rendered_count;
903    }
904}
905
906impl<'a> sum_tree::Dimension<'a, ListItemSummary> for UnrenderedCount {
907    fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
908        self.0 += summary.unrendered_count;
909    }
910}
911
912impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
913    fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
914        self.0 += summary.height;
915    }
916}
917
918impl<'a> sum_tree::SeekTarget<'a, ListItemSummary, ListItemSummary> for Count {
919    fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
920        self.0.partial_cmp(&other.count).unwrap()
921    }
922}
923
924impl<'a> sum_tree::SeekTarget<'a, ListItemSummary, ListItemSummary> for Height {
925    fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
926        self.0.partial_cmp(&other.height).unwrap()
927    }
928}
929
930#[cfg(test)]
931mod test {
932
933    use gpui::{ScrollDelta, ScrollWheelEvent};
934
935    use crate::{self as gpui, TestAppContext};
936
937    #[gpui::test]
938    fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
939        use crate::{div, list, point, px, size, Element, ListState, Styled};
940
941        let cx = cx.add_empty_window();
942
943        let state = ListState::new(5, crate::ListAlignment::Top, px(10.), |_, _| {
944            div().h(px(10.)).w_full().into_any()
945        });
946
947        // Ensure that the list is scrolled to the top
948        state.scroll_to(gpui::ListOffset {
949            item_ix: 0,
950            offset_in_item: px(0.0),
951        });
952
953        // Paint
954        cx.draw(
955            point(px(0.), px(0.)),
956            size(px(100.), px(20.)).into(),
957            |_| list(state.clone()).w_full().h_full().into_any(),
958        );
959
960        // Reset
961        state.reset(5);
962
963        // And then receive a scroll event _before_ the next paint
964        cx.simulate_event(ScrollWheelEvent {
965            position: point(px(1.), px(1.)),
966            delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
967            ..Default::default()
968        });
969
970        // Scroll position should stay at the top of the list
971        assert_eq!(state.logical_scroll_top().item_ix, 0);
972        assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
973    }
974}