list.rs

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