list.rs

  1use crate::{
  2    point, px, AnyElement, AvailableSpace, BorrowAppContext, BorrowWindow, Bounds, ContentMask,
  3    DispatchPhase, Element, IntoElement, Pixels, Point, ScrollWheelEvent, Size, Style,
  4    StyleRefinement, Styled, WindowContext,
  5};
  6use collections::VecDeque;
  7use refineable::Refineable as _;
  8use std::{cell::RefCell, ops::Range, rc::Rc};
  9use sum_tree::{Bias, SumTree};
 10
 11pub fn list(state: ListState) -> List {
 12    List {
 13        state,
 14        style: StyleRefinement::default(),
 15    }
 16}
 17
 18pub struct List {
 19    state: ListState,
 20    style: StyleRefinement,
 21}
 22
 23#[derive(Clone)]
 24pub struct ListState(Rc<RefCell<StateInner>>);
 25
 26struct StateInner {
 27    last_layout_bounds: Option<Bounds<Pixels>>,
 28    render_item: Box<dyn FnMut(usize, &mut WindowContext) -> AnyElement>,
 29    items: SumTree<ListItem>,
 30    logical_scroll_top: Option<ListOffset>,
 31    alignment: ListAlignment,
 32    overdraw: Pixels,
 33    reset: bool,
 34    #[allow(clippy::type_complexity)]
 35    scroll_handler: Option<Box<dyn FnMut(&ListScrollEvent, &mut WindowContext)>>,
 36}
 37
 38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 39pub enum ListAlignment {
 40    Top,
 41    Bottom,
 42}
 43
 44pub struct ListScrollEvent {
 45    pub visible_range: Range<usize>,
 46    pub count: usize,
 47    pub is_scrolled: bool,
 48}
 49
 50#[derive(Clone)]
 51enum ListItem {
 52    Unrendered,
 53    Rendered { height: Pixels },
 54}
 55
 56#[derive(Clone, Debug, Default, PartialEq)]
 57struct ListItemSummary {
 58    count: usize,
 59    rendered_count: usize,
 60    unrendered_count: usize,
 61    height: Pixels,
 62}
 63
 64#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
 65struct Count(usize);
 66
 67#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
 68struct RenderedCount(usize);
 69
 70#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
 71struct UnrenderedCount(usize);
 72
 73#[derive(Clone, Debug, Default)]
 74struct Height(Pixels);
 75
 76impl ListState {
 77    pub fn new<F>(
 78        element_count: usize,
 79        orientation: ListAlignment,
 80        overdraw: Pixels,
 81        render_item: F,
 82    ) -> Self
 83    where
 84        F: 'static + FnMut(usize, &mut WindowContext) -> AnyElement,
 85    {
 86        let mut items = SumTree::new();
 87        items.extend((0..element_count).map(|_| ListItem::Unrendered), &());
 88        Self(Rc::new(RefCell::new(StateInner {
 89            last_layout_bounds: None,
 90            render_item: Box::new(render_item),
 91            items,
 92            logical_scroll_top: None,
 93            alignment: orientation,
 94            overdraw,
 95            scroll_handler: None,
 96            reset: false,
 97        })))
 98    }
 99
100    /// Reset this instantiation of the list state.
101    ///
102    /// Note that this will cause scroll events to be dropped until the next paint.
103    pub fn reset(&self, element_count: usize) {
104        let state = &mut *self.0.borrow_mut();
105        state.reset = true;
106
107        state.logical_scroll_top = None;
108        state.items = SumTree::new();
109        state
110            .items
111            .extend((0..element_count).map(|_| ListItem::Unrendered), &());
112    }
113
114    pub fn item_count(&self) -> usize {
115        self.0.borrow().items.summary().count
116    }
117
118    pub fn splice(&self, old_range: Range<usize>, count: usize) {
119        let state = &mut *self.0.borrow_mut();
120
121        if let Some(ListOffset {
122            item_ix,
123            offset_in_item,
124        }) = state.logical_scroll_top.as_mut()
125        {
126            if old_range.contains(item_ix) {
127                *item_ix = old_range.start;
128                *offset_in_item = px(0.);
129            } else if old_range.end <= *item_ix {
130                *item_ix = *item_ix - (old_range.end - old_range.start) + count;
131            }
132        }
133
134        let mut old_heights = state.items.cursor::<Count>();
135        let mut new_heights = old_heights.slice(&Count(old_range.start), Bias::Right, &());
136        old_heights.seek_forward(&Count(old_range.end), Bias::Right, &());
137
138        new_heights.extend((0..count).map(|_| ListItem::Unrendered), &());
139        new_heights.append(old_heights.suffix(&()), &());
140        drop(old_heights);
141        state.items = new_heights;
142    }
143
144    pub fn set_scroll_handler(
145        &self,
146        handler: impl FnMut(&ListScrollEvent, &mut WindowContext) + 'static,
147    ) {
148        self.0.borrow_mut().scroll_handler = Some(Box::new(handler))
149    }
150
151    pub fn logical_scroll_top(&self) -> ListOffset {
152        self.0.borrow().logical_scroll_top()
153    }
154
155    pub fn scroll_to(&self, mut scroll_top: ListOffset) {
156        let state = &mut *self.0.borrow_mut();
157        let item_count = state.items.summary().count;
158        if scroll_top.item_ix >= item_count {
159            scroll_top.item_ix = item_count;
160            scroll_top.offset_in_item = px(0.);
161        }
162
163        state.logical_scroll_top = Some(scroll_top);
164    }
165
166    pub fn scroll_to_reveal_item(&self, ix: usize) {
167        let state = &mut *self.0.borrow_mut();
168
169        let mut scroll_top = state.logical_scroll_top();
170        let height = state
171            .last_layout_bounds
172            .map_or(px(0.), |bounds| bounds.size.height);
173
174        if ix <= scroll_top.item_ix {
175            scroll_top.item_ix = ix;
176            scroll_top.offset_in_item = px(0.);
177        } else {
178            let mut cursor = state.items.cursor::<ListItemSummary>();
179            cursor.seek(&Count(ix + 1), Bias::Right, &());
180            let bottom = cursor.start().height;
181            let goal_top = px(0.).max(bottom - height);
182
183            cursor.seek(&Height(goal_top), Bias::Left, &());
184            let start_ix = cursor.start().count;
185            let start_item_top = cursor.start().height;
186
187            if start_ix >= scroll_top.item_ix {
188                scroll_top.item_ix = start_ix;
189                scroll_top.offset_in_item = goal_top - start_item_top;
190            }
191        }
192
193        state.logical_scroll_top = Some(scroll_top);
194    }
195
196    /// Get the bounds for the given item in window coordinates.
197    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
198        let state = &*self.0.borrow();
199
200        let bounds = state.last_layout_bounds.unwrap_or_default();
201        let scroll_top = state.logical_scroll_top();
202        if ix < scroll_top.item_ix {
203            return None;
204        }
205
206        let mut cursor = state.items.cursor::<(Count, Height)>();
207        cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
208
209        let scroll_top = cursor.start().1 .0 + scroll_top.offset_in_item;
210
211        cursor.seek_forward(&Count(ix), Bias::Right, &());
212        if let Some(&ListItem::Rendered { height }) = cursor.item() {
213            let &(Count(count), Height(top)) = cursor.start();
214            if count == ix {
215                let top = bounds.top() + top - scroll_top;
216                return Some(Bounds::from_corners(
217                    point(bounds.left(), top),
218                    point(bounds.right(), top + height),
219                ));
220            }
221        }
222        None
223    }
224}
225
226impl StateInner {
227    fn visible_range(&self, height: Pixels, scroll_top: &ListOffset) -> Range<usize> {
228        let mut cursor = self.items.cursor::<ListItemSummary>();
229        cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
230        let start_y = cursor.start().height + scroll_top.offset_in_item;
231        cursor.seek_forward(&Height(start_y + height), Bias::Left, &());
232        scroll_top.item_ix..cursor.start().count + 1
233    }
234
235    fn scroll(
236        &mut self,
237        scroll_top: &ListOffset,
238        height: Pixels,
239        delta: Point<Pixels>,
240        cx: &mut WindowContext,
241    ) {
242        // Drop scroll events after a reset, since we can't calculate
243        // the new logical scroll top without the item heights
244        if self.reset {
245            return;
246        }
247
248        let scroll_max = (self.items.summary().height - height).max(px(0.));
249        let new_scroll_top = (self.scroll_top(scroll_top) - delta.y)
250            .max(px(0.))
251            .min(scroll_max);
252
253        if self.alignment == ListAlignment::Bottom && new_scroll_top == scroll_max {
254            self.logical_scroll_top = None;
255        } else {
256            let mut cursor = self.items.cursor::<ListItemSummary>();
257            cursor.seek(&Height(new_scroll_top), Bias::Right, &());
258            let item_ix = cursor.start().count;
259            let offset_in_item = new_scroll_top - cursor.start().height;
260            self.logical_scroll_top = Some(ListOffset {
261                item_ix,
262                offset_in_item,
263            });
264        }
265
266        if self.scroll_handler.is_some() {
267            let visible_range = self.visible_range(height, scroll_top);
268            self.scroll_handler.as_mut().unwrap()(
269                &ListScrollEvent {
270                    visible_range,
271                    count: self.items.summary().count,
272                    is_scrolled: self.logical_scroll_top.is_some(),
273                },
274                cx,
275            );
276        }
277
278        cx.refresh();
279    }
280
281    fn logical_scroll_top(&self) -> ListOffset {
282        self.logical_scroll_top
283            .unwrap_or_else(|| match self.alignment {
284                ListAlignment::Top => ListOffset {
285                    item_ix: 0,
286                    offset_in_item: px(0.),
287                },
288                ListAlignment::Bottom => ListOffset {
289                    item_ix: self.items.summary().count,
290                    offset_in_item: px(0.),
291                },
292            })
293    }
294
295    fn scroll_top(&self, logical_scroll_top: &ListOffset) -> Pixels {
296        let mut cursor = self.items.cursor::<ListItemSummary>();
297        cursor.seek(&Count(logical_scroll_top.item_ix), Bias::Right, &());
298        cursor.start().height + logical_scroll_top.offset_in_item
299    }
300}
301
302impl std::fmt::Debug for ListItem {
303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        match self {
305            Self::Unrendered => write!(f, "Unrendered"),
306            Self::Rendered { height, .. } => {
307                f.debug_struct("Rendered").field("height", height).finish()
308            }
309        }
310    }
311}
312
313#[derive(Debug, Clone, Copy, Default)]
314pub struct ListOffset {
315    pub item_ix: usize,
316    pub offset_in_item: Pixels,
317}
318
319impl Element for List {
320    type State = ();
321
322    fn request_layout(
323        &mut self,
324        _state: Option<Self::State>,
325        cx: &mut crate::WindowContext,
326    ) -> (crate::LayoutId, Self::State) {
327        let mut style = Style::default();
328        style.refine(&self.style);
329        let layout_id = cx.with_text_style(style.text_style().cloned(), |cx| {
330            cx.request_layout(&style, None)
331        });
332        (layout_id, ())
333    }
334
335    fn paint(
336        &mut self,
337        bounds: Bounds<crate::Pixels>,
338        _state: &mut Self::State,
339        cx: &mut crate::WindowContext,
340    ) {
341        let state = &mut *self.state.0.borrow_mut();
342
343        state.reset = false;
344
345        // If the width of the list has changed, invalidate all cached item heights
346        if state.last_layout_bounds.map_or(true, |last_bounds| {
347            last_bounds.size.width != bounds.size.width
348        }) {
349            state.items = SumTree::from_iter(
350                (0..state.items.summary().count).map(|_| ListItem::Unrendered),
351                &(),
352            )
353        }
354
355        let old_items = state.items.clone();
356        let mut measured_items = VecDeque::new();
357        let mut item_elements = VecDeque::new();
358        let mut rendered_height = px(0.);
359        let mut scroll_top = state.logical_scroll_top();
360
361        let available_item_space = Size {
362            width: AvailableSpace::Definite(bounds.size.width),
363            height: AvailableSpace::MinContent,
364        };
365
366        let mut cursor = old_items.cursor::<Count>();
367
368        // Render items after the scroll top, including those in the trailing overdraw
369        cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
370        for (ix, item) in cursor.by_ref().enumerate() {
371            let visible_height = rendered_height - scroll_top.offset_in_item;
372            if visible_height >= bounds.size.height + state.overdraw {
373                break;
374            }
375
376            // Use the previously cached height if available
377            let mut height = if let ListItem::Rendered { height } = item {
378                Some(*height)
379            } else {
380                None
381            };
382
383            // If we're within the visible area or the height wasn't cached, render and measure the item's element
384            if visible_height < bounds.size.height || height.is_none() {
385                let mut element = (state.render_item)(scroll_top.item_ix + ix, cx);
386                let element_size = element.measure(available_item_space, cx);
387                height = Some(element_size.height);
388                if visible_height < bounds.size.height {
389                    item_elements.push_back(element);
390                }
391            }
392
393            let height = height.unwrap();
394            rendered_height += height;
395            measured_items.push_back(ListItem::Rendered { height });
396        }
397
398        // Prepare to start walking upward from the item at the scroll top.
399        cursor.seek(&Count(scroll_top.item_ix), Bias::Right, &());
400
401        // If the rendered items do not fill the visible region, then adjust
402        // the scroll top upward.
403        if rendered_height - scroll_top.offset_in_item < bounds.size.height {
404            while rendered_height < bounds.size.height {
405                cursor.prev(&());
406                if cursor.item().is_some() {
407                    let mut element = (state.render_item)(cursor.start().0, cx);
408                    let element_size = element.measure(available_item_space, cx);
409
410                    rendered_height += element_size.height;
411                    measured_items.push_front(ListItem::Rendered {
412                        height: element_size.height,
413                    });
414                    item_elements.push_front(element)
415                } else {
416                    break;
417                }
418            }
419
420            scroll_top = ListOffset {
421                item_ix: cursor.start().0,
422                offset_in_item: rendered_height - bounds.size.height,
423            };
424
425            match state.alignment {
426                ListAlignment::Top => {
427                    scroll_top.offset_in_item = scroll_top.offset_in_item.max(px(0.));
428                    state.logical_scroll_top = Some(scroll_top);
429                }
430                ListAlignment::Bottom => {
431                    scroll_top = ListOffset {
432                        item_ix: cursor.start().0,
433                        offset_in_item: rendered_height - bounds.size.height,
434                    };
435                    state.logical_scroll_top = None;
436                }
437            };
438        }
439
440        // Measure items in the leading overdraw
441        let mut leading_overdraw = scroll_top.offset_in_item;
442        while leading_overdraw < state.overdraw {
443            cursor.prev(&());
444            if let Some(item) = cursor.item() {
445                let height = if let ListItem::Rendered { height } = item {
446                    *height
447                } else {
448                    let mut element = (state.render_item)(cursor.start().0, cx);
449                    element.measure(available_item_space, cx).height
450                };
451
452                leading_overdraw += height;
453                measured_items.push_front(ListItem::Rendered { height });
454            } else {
455                break;
456            }
457        }
458
459        let measured_range = cursor.start().0..(cursor.start().0 + measured_items.len());
460        let mut cursor = old_items.cursor::<Count>();
461        let mut new_items = cursor.slice(&Count(measured_range.start), Bias::Right, &());
462        new_items.extend(measured_items, &());
463        cursor.seek(&Count(measured_range.end), Bias::Right, &());
464        new_items.append(cursor.suffix(&()), &());
465
466        // Paint the visible items
467        cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
468            let mut item_origin = bounds.origin;
469            item_origin.y -= scroll_top.offset_in_item;
470            for item_element in &mut item_elements {
471                let item_height = item_element.measure(available_item_space, cx).height;
472                item_element.draw(item_origin, available_item_space, cx);
473                item_origin.y += item_height;
474            }
475        });
476
477        state.items = new_items;
478        state.last_layout_bounds = Some(bounds);
479
480        let list_state = self.state.clone();
481        let height = bounds.size.height;
482
483        cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
484            if phase == DispatchPhase::Bubble
485                && bounds.contains(&event.position)
486                && cx.was_top_layer(&event.position, cx.stacking_order())
487            {
488                list_state.0.borrow_mut().scroll(
489                    &scroll_top,
490                    height,
491                    event.delta.pixel_delta(px(20.)),
492                    cx,
493                )
494            }
495        });
496    }
497}
498
499impl IntoElement for List {
500    type Element = Self;
501
502    fn element_id(&self) -> Option<crate::ElementId> {
503        None
504    }
505
506    fn into_element(self) -> Self::Element {
507        self
508    }
509}
510
511impl Styled for List {
512    fn style(&mut self) -> &mut StyleRefinement {
513        &mut self.style
514    }
515}
516
517impl sum_tree::Item for ListItem {
518    type Summary = ListItemSummary;
519
520    fn summary(&self) -> Self::Summary {
521        match self {
522            ListItem::Unrendered => ListItemSummary {
523                count: 1,
524                rendered_count: 0,
525                unrendered_count: 1,
526                height: px(0.),
527            },
528            ListItem::Rendered { height } => ListItemSummary {
529                count: 1,
530                rendered_count: 1,
531                unrendered_count: 0,
532                height: *height,
533            },
534        }
535    }
536}
537
538impl sum_tree::Summary for ListItemSummary {
539    type Context = ();
540
541    fn add_summary(&mut self, summary: &Self, _: &()) {
542        self.count += summary.count;
543        self.rendered_count += summary.rendered_count;
544        self.unrendered_count += summary.unrendered_count;
545        self.height += summary.height;
546    }
547}
548
549impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Count {
550    fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
551        self.0 += summary.count;
552    }
553}
554
555impl<'a> sum_tree::Dimension<'a, ListItemSummary> for RenderedCount {
556    fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
557        self.0 += summary.rendered_count;
558    }
559}
560
561impl<'a> sum_tree::Dimension<'a, ListItemSummary> for UnrenderedCount {
562    fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
563        self.0 += summary.unrendered_count;
564    }
565}
566
567impl<'a> sum_tree::Dimension<'a, ListItemSummary> for Height {
568    fn add_summary(&mut self, summary: &'a ListItemSummary, _: &()) {
569        self.0 += summary.height;
570    }
571}
572
573impl<'a> sum_tree::SeekTarget<'a, ListItemSummary, ListItemSummary> for Count {
574    fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
575        self.0.partial_cmp(&other.count).unwrap()
576    }
577}
578
579impl<'a> sum_tree::SeekTarget<'a, ListItemSummary, ListItemSummary> for Height {
580    fn cmp(&self, other: &ListItemSummary, _: &()) -> std::cmp::Ordering {
581        self.0.partial_cmp(&other.height).unwrap()
582    }
583}
584
585#[cfg(test)]
586mod test {
587
588    use gpui::{ScrollDelta, ScrollWheelEvent};
589
590    use crate::{self as gpui, TestAppContext};
591
592    #[gpui::test]
593    fn test_reset_after_paint_before_scroll(cx: &mut TestAppContext) {
594        use crate::{div, list, point, px, size, Element, ListState, Styled};
595
596        let cx = cx.add_empty_window();
597
598        let state = ListState::new(5, crate::ListAlignment::Top, px(10.), |_, _| {
599            div().h(px(10.)).w_full().into_any()
600        });
601
602        // Ensure that the list is scrolled to the top
603        state.scroll_to(gpui::ListOffset {
604            item_ix: 0,
605            offset_in_item: px(0.0),
606        });
607
608        // Paint
609        cx.draw(
610            point(px(0.), px(0.)),
611            size(px(100.), px(20.)).into(),
612            |_| list(state.clone()).w_full().h_full().z_index(10).into_any(),
613        );
614
615        // Reset
616        state.reset(5);
617
618        // And then receive a scroll event _before_ the next paint
619        cx.simulate_event(ScrollWheelEvent {
620            position: point(px(1.), px(1.)),
621            delta: ScrollDelta::Pixels(point(px(0.), px(-500.))),
622            ..Default::default()
623        });
624
625        // Scroll position should stay at the top of the list
626        assert_eq!(state.logical_scroll_top().item_ix, 0);
627        assert_eq!(state.logical_scroll_top().offset_in_item, px(0.));
628    }
629}