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