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