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 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, 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 + padding.top),
200 bounds.lower_right()
201 - point(border.right + padding.right, border.bottom + padding.bottom),
202 );
203
204 cx.with_z_index(style.z_index.unwrap_or(0), |cx| {
205 style.paint(bounds, cx, |cx| {
206 if self.item_count > 0 {
207 if let Some(scroll_handle) = self.scroll_handle.clone() {
208 scroll_handle.0.borrow_mut().replace(ScrollHandleState {
209 item_height,
210 list_height: padded_bounds.size.height,
211 scroll_offset: shared_scroll_offset,
212 });
213 }
214
215 let first_visible_element_ix =
216 (-scroll_offset.y / item_height).floor() as usize;
217 let last_visible_element_ix =
218 ((-scroll_offset.y + padded_bounds.size.height) / item_height)
219 .ceil() as usize;
220 let visible_range = first_visible_element_ix
221 ..cmp::min(last_visible_element_ix, self.item_count);
222
223 let items = (self.render_items)(visible_range.clone(), cx);
224 cx.with_z_index(1, |cx| {
225 let content_mask = ContentMask { bounds };
226 cx.with_content_mask(Some(content_mask), |cx| {
227 for (item, ix) in items.into_iter().zip(visible_range) {
228 let item_origin = padded_bounds.origin
229 + point(px(0.), item_height * ix + scroll_offset.y);
230 let available_space = size(
231 AvailableSpace::Definite(padded_bounds.size.width),
232 AvailableSpace::Definite(item_height),
233 );
234 item.draw(item_origin, available_space, cx);
235 }
236 });
237 });
238 }
239 });
240 })
241 },
242 );
243 }
244}
245
246impl IntoElement for UniformList {
247 type Element = Self;
248
249 fn element_id(&self) -> Option<crate::ElementId> {
250 Some(self.id.clone())
251 }
252
253 fn into_element(self) -> Self::Element {
254 self
255 }
256}
257
258impl UniformList {
259 pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
260 self.item_to_measure_index = item_index.unwrap_or(0);
261 self
262 }
263
264 fn measure_item(&self, list_width: Option<Pixels>, cx: &mut WindowContext) -> Size<Pixels> {
265 if self.item_count == 0 {
266 return Size::default();
267 }
268
269 let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
270 let mut items = (self.render_items)(item_ix..item_ix + 1, cx);
271 let mut item_to_measure = items.pop().unwrap();
272 let available_space = size(
273 list_width.map_or(AvailableSpace::MinContent, |width| {
274 AvailableSpace::Definite(width)
275 }),
276 AvailableSpace::MinContent,
277 );
278 item_to_measure.measure(available_space, cx)
279 }
280
281 pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
282 self.scroll_handle = Some(handle);
283 self
284 }
285}
286
287impl InteractiveElement for UniformList {
288 fn interactivity(&mut self) -> &mut crate::Interactivity {
289 &mut self.interactivity
290 }
291}