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
147 let height = match available_space.height {
148 AvailableSpace::Definite(height) => desired_height.min(height),
149 AvailableSpace::MinContent | AvailableSpace::MaxContent => {
150 desired_height
151 }
152 };
153 size(width, height)
154 },
155 )
156 });
157
158 let element_state = UniformListState {
159 interactive,
160 item_size,
161 };
162
163 (layout_id, element_state)
164 }
165
166 fn paint(
167 &mut self,
168 bounds: Bounds<crate::Pixels>,
169 element_state: &mut Self::State,
170 cx: &mut WindowContext,
171 ) {
172 let style =
173 self.interactivity
174 .compute_style(Some(bounds), &mut element_state.interactive, cx);
175 let border = style.border_widths.to_pixels(cx.rem_size());
176 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
177
178 let padded_bounds = Bounds::from_corners(
179 bounds.origin + point(border.left + padding.left, border.top + padding.top),
180 bounds.lower_right()
181 - point(border.right + padding.right, border.bottom + padding.bottom),
182 );
183
184 let item_size = element_state.item_size;
185 let content_size = Size {
186 width: padded_bounds.size.width,
187 height: item_size.height * self.item_count + padding.top + padding.bottom,
188 };
189
190 let shared_scroll_offset = element_state
191 .interactive
192 .scroll_offset
193 .get_or_insert_with(Rc::default)
194 .clone();
195
196 let item_height = self.measure_item(Some(padded_bounds.size.width), cx).height;
197
198 self.interactivity.paint(
199 bounds,
200 content_size,
201 &mut element_state.interactive,
202 cx,
203 |style, mut scroll_offset, cx| {
204 let border = style.border_widths.to_pixels(cx.rem_size());
205 let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());
206
207 let padded_bounds = Bounds::from_corners(
208 bounds.origin + point(border.left + padding.left, border.top),
209 bounds.lower_right() - point(border.right + padding.right, border.bottom),
210 );
211
212 style.paint(bounds, cx, |cx| {
213 if self.item_count > 0 {
214 let content_height =
215 item_height * self.item_count + padding.top + padding.bottom;
216 let min_scroll_offset = padded_bounds.size.height - content_height;
217 let is_scrolled = scroll_offset.y != px(0.);
218
219 if is_scrolled && scroll_offset.y < min_scroll_offset {
220 shared_scroll_offset.borrow_mut().y = min_scroll_offset;
221 scroll_offset.y = min_scroll_offset;
222 }
223
224 if let Some(scroll_handle) = self.scroll_handle.clone() {
225 scroll_handle.0.borrow_mut().replace(ScrollHandleState {
226 item_height,
227 list_height: padded_bounds.size.height,
228 scroll_offset: shared_scroll_offset,
229 });
230 }
231
232 let first_visible_element_ix =
233 (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
234 let last_visible_element_ix =
235 ((-scroll_offset.y + padded_bounds.size.height) / item_height).ceil()
236 as usize;
237 let visible_range = first_visible_element_ix
238 ..cmp::min(last_visible_element_ix, self.item_count);
239
240 let mut items = (self.render_items)(visible_range.clone(), cx);
241 cx.with_z_index(1, |cx| {
242 let content_mask = ContentMask { bounds };
243 cx.with_content_mask(Some(content_mask), |cx| {
244 for (item, ix) in items.iter_mut().zip(visible_range) {
245 let item_origin = padded_bounds.origin
246 + point(
247 px(0.),
248 item_height * ix + scroll_offset.y + padding.top,
249 );
250 let available_space = size(
251 AvailableSpace::Definite(padded_bounds.size.width),
252 AvailableSpace::Definite(item_height),
253 );
254 item.draw(item_origin, available_space, cx);
255 }
256 });
257 });
258 }
259 });
260 },
261 )
262 }
263}
264
265impl IntoElement for UniformList {
266 type Element = Self;
267
268 fn element_id(&self) -> Option<crate::ElementId> {
269 Some(self.id.clone())
270 }
271
272 fn into_element(self) -> Self::Element {
273 self
274 }
275}
276
277impl UniformList {
278 pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
279 self.item_to_measure_index = item_index.unwrap_or(0);
280 self
281 }
282
283 fn measure_item(&self, list_width: Option<Pixels>, cx: &mut WindowContext) -> Size<Pixels> {
284 if self.item_count == 0 {
285 return Size::default();
286 }
287
288 let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
289 let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
290 let mut item_to_measure = items.pop().unwrap();
291 let available_space = size(
292 list_width.map_or(AvailableSpace::MinContent, |width| {
293 AvailableSpace::Definite(width)
294 }),
295 AvailableSpace::MinContent,
296 );
297 item_to_measure.measure(available_space, cx)
298 }
299
300 pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
301 self.scroll_handle = Some(handle);
302 self
303 }
304}
305
306impl InteractiveElement for UniformList {
307 fn interactivity(&mut self) -> &mut crate::Interactivity {
308 &mut self.interactivity
309 }
310}