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