1use crate::{
2 point, px, size, AnyElement, AvailableSpace, BorrowWindow, Bounds, ContentMask, Element,
3 ElementId, InteractiveElement, InteractiveElementState, Interactivity, IntoElement, LayoutId,
4 Pixels, Render, Size, StyleRefinement, Styled, View, ViewContext, WindowContext,
5};
6use smallvec::SmallVec;
7use std::{cell::RefCell, cmp, ops::Range, rc::Rc};
8use taffy::style::Overflow;
9
10/// uniform_list provides lazy rendering for a set of items that are of uniform height.
11/// When rendered into a container with overflow-y: hidden and a fixed (or max) height,
12/// uniform_list will only render the visible subset of items.
13#[track_caller]
14pub fn uniform_list<I, R, V>(
15 view: View<V>,
16 id: I,
17 item_count: usize,
18 f: impl 'static + Fn(&mut V, Range<usize>, &mut ViewContext<V>) -> Vec<R>,
19) -> UniformList
20where
21 I: Into<ElementId>,
22 R: IntoElement,
23 V: Render,
24{
25 let id = id.into();
26 let mut base_style = StyleRefinement::default();
27 base_style.overflow.y = Some(Overflow::Scroll);
28
29 let render_range = move |range, cx: &mut WindowContext| {
30 view.update(cx, |this, cx| {
31 f(this, range, cx)
32 .into_iter()
33 .map(|component| component.into_any_element())
34 .collect()
35 })
36 };
37
38 UniformList {
39 id: id.clone(),
40 item_count,
41 item_to_measure_index: 0,
42 render_items: Box::new(render_range),
43 interactivity: Interactivity {
44 element_id: Some(id),
45 base_style: Box::new(base_style),
46
47 #[cfg(debug_assertions)]
48 location: Some(*core::panic::Location::caller()),
49
50 ..Default::default()
51 },
52 scroll_handle: None,
53 }
54}
55
56pub struct UniformList {
57 id: ElementId,
58 item_count: usize,
59 item_to_measure_index: usize,
60 render_items:
61 Box<dyn for<'a> Fn(Range<usize>, &'a mut WindowContext) -> SmallVec<[AnyElement; 64]>>,
62 interactivity: Interactivity,
63 scroll_handle: Option<UniformListScrollHandle>,
64}
65
66#[derive(Clone, Default)]
67pub struct UniformListScrollHandle {
68 deferred_scroll_to_item: Rc<RefCell<Option<usize>>>,
69}
70
71impl UniformListScrollHandle {
72 pub fn new() -> Self {
73 Self {
74 deferred_scroll_to_item: Rc::new(RefCell::new(None)),
75 }
76 }
77
78 pub fn scroll_to_item(&mut self, ix: usize) {
79 self.deferred_scroll_to_item.replace(Some(ix));
80 }
81}
82
83impl Styled for UniformList {
84 fn style(&mut self) -> &mut StyleRefinement {
85 &mut self.interactivity.base_style
86 }
87}
88
89#[derive(Default)]
90pub struct UniformListState {
91 interactive: InteractiveElementState,
92 item_size: Size<Pixels>,
93}
94
95impl Element for UniformList {
96 type State = UniformListState;
97
98 fn request_layout(
99 &mut self,
100 state: Option<Self::State>,
101 cx: &mut WindowContext,
102 ) -> (LayoutId, Self::State) {
103 let max_items = self.item_count;
104 let item_size = state
105 .as_ref()
106 .map(|s| s.item_size)
107 .unwrap_or_else(|| self.measure_item(None, cx));
108
109 let (layout_id, interactive) =
110 self.interactivity
111 .layout(state.map(|s| s.interactive), cx, |style, cx| {
112 cx.request_measured_layout(
113 style,
114 move |known_dimensions, available_space, _cx| {
115 let desired_height = item_size.height * max_items;
116 let width =
117 known_dimensions
118 .width
119 .unwrap_or(match available_space.width {
120 AvailableSpace::Definite(x) => x,
121 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
122 item_size.width
123 }
124 });
125
126 let height = match available_space.height {
127 AvailableSpace::Definite(height) => desired_height.min(height),
128 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
129 desired_height
130 }
131 };
132 size(width, height)
133 },
134 )
135 });
136
137 let element_state = UniformListState {
138 interactive,
139 item_size,
140 };
141
142 (layout_id, element_state)
143 }
144
145 fn paint(
146 &mut self,
147 bounds: Bounds<crate::Pixels>,
148 element_state: &mut Self::State,
149 cx: &mut WindowContext,
150 ) {
151 let style =
152 self.interactivity
153 .compute_style(Some(bounds), &mut element_state.interactive, cx);
154 let border = style.border_widths.to_pixels(cx.rem_size());
155 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
156
157 let padded_bounds = Bounds::from_corners(
158 bounds.origin + point(border.left + padding.left, border.top + padding.top),
159 bounds.lower_right()
160 - point(border.right + padding.right, border.bottom + padding.bottom),
161 );
162
163 let item_size = element_state.item_size;
164 let content_size = Size {
165 width: padded_bounds.size.width,
166 height: item_size.height * self.item_count + padding.top + padding.bottom,
167 };
168
169 let shared_scroll_offset = element_state
170 .interactive
171 .scroll_offset
172 .get_or_insert_with(|| Rc::default())
173 .clone();
174
175 let item_height = self.measure_item(Some(padded_bounds.size.width), cx).height;
176 let shared_scroll_to_item = self
177 .scroll_handle
178 .as_mut()
179 .and_then(|handle| handle.deferred_scroll_to_item.take());
180
181 self.interactivity.paint(
182 bounds,
183 content_size,
184 &mut element_state.interactive,
185 cx,
186 |style, mut scroll_offset, cx| {
187 let border = style.border_widths.to_pixels(cx.rem_size());
188 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
189
190 let padded_bounds = Bounds::from_corners(
191 bounds.origin + point(border.left + padding.left, border.top),
192 bounds.lower_right() - point(border.right + padding.right, border.bottom),
193 );
194
195 if self.item_count > 0 {
196 let content_height =
197 item_height * self.item_count + padding.top + padding.bottom;
198 let min_scroll_offset = padded_bounds.size.height - content_height;
199 let is_scrolled = scroll_offset.y != px(0.);
200
201 if is_scrolled && scroll_offset.y < min_scroll_offset {
202 shared_scroll_offset.borrow_mut().y = min_scroll_offset;
203 scroll_offset.y = min_scroll_offset;
204 }
205
206 if let Some(ix) = shared_scroll_to_item {
207 let list_height = padded_bounds.size.height;
208 let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
209 let item_top = item_height * ix;
210 let item_bottom = item_top + item_height;
211 let scroll_top = -updated_scroll_offset.y;
212 if item_top < scroll_top {
213 updated_scroll_offset.y = -item_top;
214 } else if item_bottom > scroll_top + list_height {
215 updated_scroll_offset.y = -(item_bottom - list_height);
216 }
217 scroll_offset = *updated_scroll_offset;
218 }
219
220 let first_visible_element_ix =
221 (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
222 let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
223 / item_height)
224 .ceil() as usize;
225 let visible_range = first_visible_element_ix
226 ..cmp::min(last_visible_element_ix, self.item_count);
227
228 let mut items = (self.render_items)(visible_range.clone(), cx);
229 cx.with_z_index(1, |cx| {
230 let content_mask = ContentMask { bounds };
231 cx.with_content_mask(Some(content_mask), |cx| {
232 for (item, ix) in items.iter_mut().zip(visible_range) {
233 let item_origin = padded_bounds.origin
234 + point(
235 px(0.),
236 item_height * ix + scroll_offset.y + padding.top,
237 );
238 let available_space = size(
239 AvailableSpace::Definite(padded_bounds.size.width),
240 AvailableSpace::Definite(item_height),
241 );
242 item.draw(item_origin, available_space, cx);
243 }
244 });
245 });
246 }
247 },
248 )
249 }
250}
251
252impl IntoElement for UniformList {
253 type Element = Self;
254
255 fn element_id(&self) -> Option<crate::ElementId> {
256 Some(self.id.clone())
257 }
258
259 fn into_element(self) -> Self::Element {
260 self
261 }
262}
263
264impl UniformList {
265 pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
266 self.item_to_measure_index = item_index.unwrap_or(0);
267 self
268 }
269
270 fn measure_item(&self, list_width: Option<Pixels>, cx: &mut WindowContext) -> Size<Pixels> {
271 if self.item_count == 0 {
272 return Size::default();
273 }
274
275 let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
276 let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
277 let mut item_to_measure = items.pop().unwrap();
278 let available_space = size(
279 list_width.map_or(AvailableSpace::MinContent, |width| {
280 AvailableSpace::Definite(width)
281 }),
282 AvailableSpace::MinContent,
283 );
284 item_to_measure.measure(available_space, cx)
285 }
286
287 pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
288 self.scroll_handle = Some(handle);
289 self
290 }
291}
292
293impl InteractiveElement for UniformList {
294 fn interactivity(&mut self) -> &mut crate::Interactivity {
295 &mut self.interactivity
296 }
297}