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