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