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 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        autoscroll: bool,
 709        render_item: &mut RenderItemFn,
 710        window: &mut Window,
 711        cx: &mut App,
 712    ) -> Result<LayoutItemsResponse, ListOffset> {
 713        window.transact(|window| {
 714            let mut layout_response = self.layout_items(
 715                Some(bounds.size.width),
 716                bounds.size.height,
 717                &padding,
 718                render_item,
 719                window,
 720                cx,
 721            );
 722
 723            // Avoid honoring autoscroll requests from elements other than our children.
 724            window.take_autoscroll();
 725
 726            // Only paint the visible items, if there is actually any space for them (taking padding into account)
 727            if bounds.size.height > padding.top + padding.bottom {
 728                let mut item_origin = bounds.origin + Point::new(px(0.), padding.top);
 729                item_origin.y -= layout_response.scroll_top.offset_in_item;
 730                for item in &mut layout_response.item_layouts {
 731                    window.with_content_mask(Some(ContentMask { bounds }), |window| {
 732                        item.element.prepaint_at(item_origin, window, cx);
 733                    });
 734
 735                    if let Some(autoscroll_bounds) = window.take_autoscroll()
 736                        && autoscroll
 737                    {
 738                        if autoscroll_bounds.top() < bounds.top() {
 739                            return Err(ListOffset {
 740                                item_ix: item.index,
 741                                offset_in_item: autoscroll_bounds.top() - item_origin.y,
 742                            });
 743                        } else if autoscroll_bounds.bottom() > bounds.bottom() {
 744                            let mut cursor = self.items.cursor::<Count>(());
 745                            cursor.seek(&Count(item.index), Bias::Right);
 746                            let mut height = bounds.size.height - padding.top - padding.bottom;
 747
 748                            // Account for the height of the element down until the autoscroll bottom.
 749                            height -= autoscroll_bounds.bottom() - item_origin.y;
 750
 751                            // Keep decreasing the scroll top until we fill all the available space.
 752                            while height > Pixels::ZERO {
 753                                cursor.prev();
 754                                let Some(item) = cursor.item() else { break };
 755
 756                                let size = item.size().unwrap_or_else(|| {
 757                                    let mut item = render_item(cursor.start().0, window, cx);
 758                                    let item_available_size =
 759                                        size(bounds.size.width.into(), AvailableSpace::MinContent);
 760                                    item.layout_as_root(item_available_size, window, cx)
 761                                });
 762                                height -= size.height;
 763                            }
 764
 765                            return Err(ListOffset {
 766                                item_ix: cursor.start().0,
 767                                offset_in_item: if height < Pixels::ZERO {
 768                                    -height
 769                                } else {
 770                                    Pixels::ZERO
 771                                },
 772                            });
 773                        }
 774                    }
 775
 776                    item_origin.y += item.size.height;
 777                }
 778            } else {
 779                layout_response.item_layouts.clear();
 780            }
 781
 782            Ok(layout_response)
 783        })
 784    }
 785
 786    // Scrollbar support
 787
 788    fn set_offset_from_scrollbar(&mut self, point: Point<Pixels>) {
 789        let Some(bounds) = self.last_layout_bounds else {
 790            return;
 791        };
 792        let height = bounds.size.height;
 793
 794        let padding = self.last_padding.unwrap_or_default();
 795        let content_height = self.items.summary().height;
 796        let scroll_max = (content_height + padding.top + padding.bottom - height).max(px(0.));
 797        let drag_offset =
 798            // if dragging the scrollbar, we want to offset the point if the height changed
 799            content_height - self.scrollbar_drag_start_height.unwrap_or(content_height);
 800        let new_scroll_top = (point.y - drag_offset).abs().max(px(0.)).min(scroll_max);
 801
 802        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
 803            self.logical_scroll_top = None;
 804        } else {
 805            let mut cursor = self.items.cursor::<ListItemSummary>(());
 806            cursor.seek(&Height(new_scroll_top), Bias::Right);
 807
 808            let item_ix = cursor.start().count;
 809            let offset_in_item = new_scroll_top - cursor.start().height;
 810            self.logical_scroll_top = Some(ListOffset {
 811                item_ix,
 812                offset_in_item,
 813            });
 814        }
 815    }
 816}
 817
 818impl std::fmt::Debug for ListItem {
 819    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 820        match self {
 821            Self::Unmeasured { .. } => write!(f, "Unrendered"),
 822            Self::Measured { size, .. } => f.debug_struct("Rendered").field("size", size).finish(),
 823        }
 824    }
 825}
 826
 827/// An offset into the list's items, in terms of the item index and the number
 828/// of pixels off the top left of the item.
 829#[derive(Debug, Clone, Copy, Default)]
 830pub struct ListOffset {
 831    /// The index of an item in the list
 832    pub item_ix: usize,
 833    /// The number of pixels to offset from the item index.
 834    pub offset_in_item: Pixels,
 835}
 836
 837impl Element for List {
 838    type RequestLayoutState = ();
 839    type PrepaintState = ListPrepaintState;
 840
 841    fn id(&self) -> Option<crate::ElementId> {
 842        None
 843    }
 844
 845    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 846        None
 847    }
 848
 849    fn request_layout(
 850        &mut self,
 851        _id: Option<&GlobalElementId>,
 852        _inspector_id: Option<&InspectorElementId>,
 853        window: &mut Window,
 854        cx: &mut App,
 855    ) -> (crate::LayoutId, Self::RequestLayoutState) {
 856        let layout_id = match self.sizing_behavior {
 857            ListSizingBehavior::Infer => {
 858                let mut style = Style::default();
 859                style.overflow.y = Overflow::Scroll;
 860                style.refine(&self.style);
 861                window.with_text_style(style.text_style().cloned(), |window| {
 862                    let state = &mut *self.state.0.borrow_mut();
 863
 864                    let available_height = if let Some(last_bounds) = state.last_layout_bounds {
 865                        last_bounds.size.height
 866                    } else {
 867                        // If we don't have the last layout bounds (first render),
 868                        // we might just use the overdraw value as the available height to layout enough items.
 869                        state.overdraw
 870                    };
 871                    let padding = style.padding.to_pixels(
 872                        state.last_layout_bounds.unwrap_or_default().size.into(),
 873                        window.rem_size(),
 874                    );
 875
 876                    let layout_response = state.layout_items(
 877                        None,
 878                        available_height,
 879                        &padding,
 880                        &mut self.render_item,
 881                        window,
 882                        cx,
 883                    );
 884                    let max_element_width = layout_response.max_item_width;
 885
 886                    let summary = state.items.summary();
 887                    let total_height = summary.height;
 888
 889                    window.request_measured_layout(
 890                        style,
 891                        move |known_dimensions, available_space, _window, _cx| {
 892                            let width =
 893                                known_dimensions
 894                                    .width
 895                                    .unwrap_or(match available_space.width {
 896                                        AvailableSpace::Definite(x) => x,
 897                                        AvailableSpace::MinContent | AvailableSpace::MaxContent => {
 898                                            max_element_width
 899                                        }
 900                                    });
 901                            let height = match available_space.height {
 902                                AvailableSpace::Definite(height) => total_height.min(height),
 903                                AvailableSpace::MinContent | AvailableSpace::MaxContent => {
 904                                    total_height
 905                                }
 906                            };
 907                            size(width, height)
 908                        },
 909                    )
 910                })
 911            }
 912            ListSizingBehavior::Auto => {
 913                let mut style = Style::default();
 914                style.refine(&self.style);
 915                window.with_text_style(style.text_style().cloned(), |window| {
 916                    window.request_layout(style, None, cx)
 917                })
 918            }
 919        };
 920        (layout_id, ())
 921    }
 922
 923    fn prepaint(
 924        &mut self,
 925        _id: Option<&GlobalElementId>,
 926        _inspector_id: Option<&InspectorElementId>,
 927        bounds: Bounds<Pixels>,
 928        _: &mut Self::RequestLayoutState,
 929        window: &mut Window,
 930        cx: &mut App,
 931    ) -> ListPrepaintState {
 932        let state = &mut *self.state.0.borrow_mut();
 933        state.reset = false;
 934
 935        let mut style = Style::default();
 936        style.refine(&self.style);
 937
 938        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
 939
 940        // If the width of the list has changed, invalidate all cached item heights
 941        if state
 942            .last_layout_bounds
 943            .is_none_or(|last_bounds| last_bounds.size.width != bounds.size.width)
 944        {
 945            let new_items = SumTree::from_iter(
 946                state.items.iter().map(|item| ListItem::Unmeasured {
 947                    focus_handle: item.focus_handle(),
 948                }),
 949                (),
 950            );
 951
 952            state.items = new_items;
 953        }
 954
 955        let padding = style
 956            .padding
 957            .to_pixels(bounds.size.into(), window.rem_size());
 958        let layout =
 959            match state.prepaint_items(bounds, padding, true, &mut self.render_item, window, cx) {
 960                Ok(layout) => layout,
 961                Err(autoscroll_request) => {
 962                    state.logical_scroll_top = Some(autoscroll_request);
 963                    state
 964                        .prepaint_items(bounds, padding, false, &mut self.render_item, window, cx)
 965                        .unwrap()
 966                }
 967            };
 968
 969        state.last_layout_bounds = Some(bounds);
 970        state.last_padding = Some(padding);
 971        ListPrepaintState { hitbox, layout }
 972    }
 973
 974    fn paint(
 975        &mut self,
 976        _id: Option<&GlobalElementId>,
 977        _inspector_id: Option<&InspectorElementId>,
 978        bounds: Bounds<crate::Pixels>,
 979        _: &mut Self::RequestLayoutState,
 980        prepaint: &mut Self::PrepaintState,
 981        window: &mut Window,
 982        cx: &mut App,
 983    ) {
 984        let current_view = window.current_view();
 985        window.with_content_mask(Some(ContentMask { bounds }), |window| {
 986            for item in &mut prepaint.layout.item_layouts {
 987                item.element.paint(window, cx);
 988            }
 989        });
 990
 991        let list_state = self.state.clone();
 992        let height = bounds.size.height;
 993        let scroll_top = prepaint.layout.scroll_top;
 994        let hitbox_id = prepaint.hitbox.id;
 995        let mut accumulated_scroll_delta = ScrollDelta::default();
 996        window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
 997            if phase == DispatchPhase::Bubble && hitbox_id.should_handle_scroll(window) {
 998                accumulated_scroll_delta = accumulated_scroll_delta.coalesce(event.delta);
 999                let pixel_delta = accumulated_scroll_delta.pixel_delta(px(20.));
1000                list_state.0.borrow_mut().scroll(
1001                    &scroll_top,
1002                    height,
1003                    pixel_delta,
1004                    current_view,
1005                    window,
1006                    cx,
1007                )
1008            }
1009        });
1010    }
1011}
1012
1013impl IntoElement for List {
1014    type Element = Self;
1015
1016    fn into_element(self) -> Self::Element {
1017        self
1018    }
1019}
1020
1021impl Styled for List {
1022    fn style(&mut self) -> &mut StyleRefinement {
1023        &mut self.style
1024    }
1025}
1026
1027impl sum_tree::Item for ListItem {
1028    type Summary = ListItemSummary;
1029
1030    fn summary(&self, _: ()) -> Self::Summary {
1031        match self {
1032            ListItem::Unmeasured { focus_handle } => ListItemSummary {
1033                count: 1,
1034                rendered_count: 0,
1035                unrendered_count: 1,
1036                height: px(0.),
1037                has_focus_handles: focus_handle.is_some(),
1038            },
1039            ListItem::Measured {
1040                size, focus_handle, ..
1041            } => ListItemSummary {
1042                count: 1,
1043                rendered_count: 1,
1044                unrendered_count: 0,
1045                height: size.height,
1046                has_focus_handles: focus_handle.is_some(),
1047            },
1048        }
1049    }
1050}
1051
1052impl sum_tree::ContextLessSummary for ListItemSummary {
1053    fn zero() -> Self {
1054        Default::default()
1055    }
1056
1057    fn add_summary(&mut self, summary: &Self) {
1058        self.count += summary.count;
1059        self.rendered_count += summary.rendered_count;
1060        self.unrendered_count += summary.unrendered_count;
1061        self.height += summary.height;
1062        self.has_focus_handles |= summary.has_focus_handles;
1063    }
1064}
1065
1066impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
1067    fn zero(_cx: ()) -> Self {
1068        Default::default()
1069    }
1070
1071    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1072        self.0 += summary.count;
1073    }
1074}
1075
1076impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
1077    fn zero(_cx: ()) -> Self {
1078        Default::default()
1079    }
1080
1081    fn add_summary(&mut self, summary: &'a ListItemSummary, _: ()) {
1082        self.0 += summary.height;
1083    }
1084}
1085
1086impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Count {
1087    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1088        self.0.partial_cmp(&other.count).unwrap()
1089    }
1090}
1091
1092impl sum_tree::SeekTarget<'_, ListItemSummary, ListItemSummary> for Height {
1093    fn cmp(&self, other: &ListItemSummary, _: ()) -> std::cmp::Ordering {
1094        self.0.partial_cmp(&other.height).unwrap()
1095    }
1096}
1097
1098#[cfg(test)]
1099mod test {
1100
1101    use gpui::{ScrollDelta, ScrollWheelEvent};
1102
1103    use crate::{self as gpui, TestAppContext};
1104
1105    #[gpui::test]
1106    fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
1107        use crate::{
1108            AppContext, Context, Element, IntoElement, ListState, Render, Styled, Window, div,
1109            list, point, px, size,
1110        };
1111
1112        let cx = cx.add_empty_window();
1113
1114        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1115
1116        // Ensure that the list is scrolled to the top
1117        state.scroll_to(gpui::ListOffset {
1118            item_ix: 0,
1119            offset_in_item: px(0.0),
1120        });
1121
1122        struct TestView(ListState);
1123        impl Render for TestView {
1124            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1125                list(self.0.clone(), |_, _, _| {
1126                    div().h(px(10.)).w_full().into_any()
1127                })
1128                .w_full()
1129                .h_full()
1130            }
1131        }
1132
1133        // Paint
1134        cx.draw(point(px(0.), px(0.)), size(px(100.), px(20.)), |_, cx| {
1135            cx.new(|_| TestView(state.clone()))
1136        });
1137
1138        // Reset
1139        state.reset(5);
1140
1141        // And then receive a scroll event _before_ the next paint
1142        cx.simulate_event(ScrollWheelEvent {
1143            position: point(px(1.), px(1.)),
1144            delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
1145            ..Default::default()
1146        });
1147
1148        // Scroll position should stay at the top of the list
1149        assert_eq!(state.logical_scroll_top().item_ix, 0);
1150        assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
1151    }
1152
1153    #[gpui::test]
1154    fn test_scroll_by_positive_and_negative_distance(cx: &mut TestAppContext) {
1155        use crate::{
1156            AppContext, Context, Element, IntoElement, ListState, Render, Styled, Window, div,
1157            list, point, px, size,
1158        };
1159
1160        let cx = cx.add_empty_window();
1161
1162        let state = ListState::new(5, crate::ListAlignment::Top, px(10.));
1163
1164        struct TestView(ListState);
1165        impl Render for TestView {
1166            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1167                list(self.0.clone(), |_, _, _| {
1168                    div().h(px(20.)).w_full().into_any()
1169                })
1170                .w_full()
1171                .h_full()
1172            }
1173        }
1174
1175        // Paint
1176        cx.draw(point(px(0.), px(0.)), size(px(100.), px(100.)), |_, cx| {
1177            cx.new(|_| TestView(state.clone()))
1178        });
1179
1180        // Test positive distance: start at item 1, move down 30px
1181        state.scroll_by(px(30.));
1182
1183        // Should move to item 2
1184        let offset = state.logical_scroll_top();
1185        assert_eq!(offset.item_ix, 1);
1186        assert_eq!(offset.offset_in_item, px(10.));
1187
1188        // Test negative distance: start at item 2, move up 30px
1189        state.scroll_by(px(-30.));
1190
1191        // Should move back to item 1
1192        let offset = state.logical_scroll_top();
1193        assert_eq!(offset.item_ix, 0);
1194        assert_eq!(offset.offset_in_item, px(0.));
1195
1196        // Test zero distance
1197        state.scroll_by(px(0.));
1198        let offset = state.logical_scroll_top();
1199        assert_eq!(offset.item_ix, 0);
1200        assert_eq!(offset.offset_in_item, px(0.));
1201    }
1202}