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