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