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