list.rs

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