1use crate::{
2 point, px, size, AnyElement, AvailableSpace, BorrowWindow, Bounds, ContentMask, Element,
3 ElementId, InteractiveElement, InteractiveElementState, Interactivity, IntoElement, LayoutId,
4 Pixels, Point, 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.into()),
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(Rc<RefCell<Option<ScrollHandleState>>>);
68
69#[derive(Clone, Debug)]
70struct ScrollHandleState {
71 item_height: Pixels,
72 list_height: Pixels,
73 scroll_offset: Rc<RefCell<Point<Pixels>>>,
74}
75
76impl UniformListScrollHandle {
77 pub fn new() -> Self {
78 Self(Rc::new(RefCell::new(None)))
79 }
80
81 pub fn scroll_to_item(&self, ix: usize) {
82 if let Some(state) = &*self.0.borrow() {
83 let mut scroll_offset = state.scroll_offset.borrow_mut();
84 let item_top = state.item_height * ix;
85 let item_bottom = item_top + state.item_height;
86 let scroll_top = -scroll_offset.y;
87 if item_top < scroll_top {
88 scroll_offset.y = -item_top;
89 } else if item_bottom > scroll_top + state.list_height {
90 scroll_offset.y = -(item_bottom - state.list_height);
91 }
92 }
93 }
94
95 pub fn scroll_top(&self) -> Pixels {
96 if let Some(state) = &*self.0.borrow() {
97 -state.scroll_offset.borrow().y
98 } else {
99 Pixels::ZERO
100 }
101 }
102}
103
104impl Styled for UniformList {
105 fn style(&mut self) -> &mut StyleRefinement {
106 &mut self.interactivity.base_style
107 }
108}
109
110#[derive(Default)]
111pub struct UniformListState {
112 interactive: InteractiveElementState,
113 item_size: Size<Pixels>,
114}
115
116impl Element for UniformList {
117 type State = UniformListState;
118
119 fn layout(
120 &mut self,
121 state: Option<Self::State>,
122 cx: &mut WindowContext,
123 ) -> (LayoutId, Self::State) {
124 let max_items = self.item_count;
125 let item_size = state
126 .as_ref()
127 .map(|s| s.item_size)
128 .unwrap_or_else(|| self.measure_item(None, cx));
129
130 let (layout_id, interactive) =
131 self.interactivity
132 .layout(state.map(|s| s.interactive), cx, |style, cx| {
133 cx.request_measured_layout(
134 style,
135 move |known_dimensions, available_space, _cx| {
136 let desired_height = item_size.height * max_items;
137 let width =
138 known_dimensions
139 .width
140 .unwrap_or(match available_space.width {
141 AvailableSpace::Definite(x) => x,
142 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
143 item_size.width
144 }
145 });
146 let height = match available_space.height {
147 AvailableSpace::Definite(height) => desired_height.min(height),
148 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
149 desired_height
150 }
151 };
152 size(width, height)
153 },
154 )
155 });
156
157 let element_state = UniformListState {
158 interactive,
159 item_size,
160 };
161
162 (layout_id, element_state)
163 }
164
165 fn paint(
166 &mut self,
167 bounds: Bounds<crate::Pixels>,
168 element_state: &mut Self::State,
169 cx: &mut WindowContext,
170 ) {
171 let style =
172 self.interactivity
173 .compute_style(Some(bounds), &mut element_state.interactive, cx);
174 let border = style.border_widths.to_pixels(cx.rem_size());
175 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
176
177 let padded_bounds = Bounds::from_corners(
178 bounds.origin + point(border.left + padding.left, border.top + padding.top),
179 bounds.lower_right()
180 - point(border.right + padding.right, border.bottom + padding.bottom),
181 );
182
183 let item_size = element_state.item_size;
184 let content_size = Size {
185 width: padded_bounds.size.width,
186 height: item_size.height * self.item_count + padding.top + padding.bottom,
187 };
188
189 let shared_scroll_offset = element_state
190 .interactive
191 .scroll_offset
192 .get_or_insert_with(Rc::default)
193 .clone();
194
195 let item_height = self.measure_item(Some(padded_bounds.size.width), cx).height;
196
197 self.interactivity.paint(
198 bounds,
199 content_size,
200 &mut element_state.interactive,
201 cx,
202 |style, mut scroll_offset, cx| {
203 let border = style.border_widths.to_pixels(cx.rem_size());
204 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
205
206 let padded_bounds = Bounds::from_corners(
207 bounds.origin + point(border.left + padding.left, border.top),
208 bounds.lower_right() - point(border.right + padding.right, border.bottom),
209 );
210
211 style.paint(bounds, cx, |cx| {
212 if self.item_count > 0 {
213 let content_height =
214 item_height * self.item_count + padding.top + padding.bottom;
215 let min_scroll_offset = padded_bounds.size.height - content_height;
216 let is_scrolled = scroll_offset.y != px(0.);
217
218 if is_scrolled && scroll_offset.y < min_scroll_offset {
219 shared_scroll_offset.borrow_mut().y = min_scroll_offset;
220 scroll_offset.y = min_scroll_offset;
221 }
222
223 if let Some(scroll_handle) = self.scroll_handle.clone() {
224 scroll_handle.0.borrow_mut().replace(ScrollHandleState {
225 item_height,
226 list_height: padded_bounds.size.height,
227 scroll_offset: shared_scroll_offset,
228 });
229 }
230
231 let first_visible_element_ix =
232 (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
233 let last_visible_element_ix =
234 ((-scroll_offset.y + padded_bounds.size.height) / item_height).ceil()
235 as usize;
236 let visible_range = first_visible_element_ix
237 ..cmp::min(last_visible_element_ix, self.item_count);
238
239 let mut items = (self.render_items)(visible_range.clone(), cx);
240 cx.with_z_index(1, |cx| {
241 let content_mask = ContentMask { bounds };
242 cx.with_content_mask(Some(content_mask), |cx| {
243 for (item, ix) in items.iter_mut().zip(visible_range) {
244 let item_origin = padded_bounds.origin
245 + point(
246 px(0.),
247 item_height * ix + scroll_offset.y + padding.top,
248 );
249 let available_space = size(
250 AvailableSpace::Definite(padded_bounds.size.width),
251 AvailableSpace::Definite(item_height),
252 );
253 item.draw(item_origin, available_space, cx);
254 }
255 });
256 });
257 }
258 });
259 },
260 )
261 }
262}
263
264impl IntoElement for UniformList {
265 type Element = Self;
266
267 fn element_id(&self) -> Option<crate::ElementId> {
268 Some(self.id.clone())
269 }
270
271 fn into_element(self) -> Self::Element {
272 self
273 }
274}
275
276impl UniformList {
277 pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
278 self.item_to_measure_index = item_index.unwrap_or(0);
279 self
280 }
281
282 fn measure_item(&self, list_width: Option<Pixels>, cx: &mut WindowContext) -> Size<Pixels> {
283 if self.item_count == 0 {
284 return Size::default();
285 }
286
287 let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
288 let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
289 let mut item_to_measure = items.pop().unwrap();
290 let available_space = size(
291 list_width.map_or(AvailableSpace::MinContent, |width| {
292 AvailableSpace::Definite(width)
293 }),
294 AvailableSpace::MinContent,
295 );
296 item_to_measure.measure(available_space, cx)
297 }
298
299 pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
300 self.scroll_handle = Some(handle);
301 self
302 }
303}
304
305impl InteractiveElement for UniformList {
306 fn interactivity(&mut self) -> &mut crate::Interactivity {
307 &mut self.interactivity
308 }
309}