1use super::{Element, Event, EventContext, LayoutContext, PaintContext, SizeConstraint};
2use crate::{
3 geometry::{
4 rect::RectF,
5 vector::{vec2f, Vector2F},
6 },
7 json::{self, json},
8 ElementBox,
9};
10use json::ToJson;
11use parking_lot::Mutex;
12use std::{cmp, ops::Range, sync::Arc};
13
14#[derive(Clone, Default)]
15pub struct UniformListState(Arc<Mutex<StateInner>>);
16
17#[derive(Debug)]
18pub enum ScrollTarget {
19 Show(usize),
20 Center(usize),
21}
22
23impl UniformListState {
24 pub fn scroll_to(&self, scroll_to: ScrollTarget) {
25 self.0.lock().scroll_to = Some(scroll_to);
26 }
27
28 pub fn scroll_top(&self) -> f32 {
29 self.0.lock().scroll_top
30 }
31}
32
33#[derive(Default)]
34struct StateInner {
35 scroll_top: f32,
36 scroll_to: Option<ScrollTarget>,
37}
38
39pub struct LayoutState {
40 scroll_max: f32,
41 item_height: f32,
42 items: Vec<ElementBox>,
43}
44
45pub struct UniformList<F>
46where
47 F: Fn(Range<usize>, &mut Vec<ElementBox>, &mut LayoutContext),
48{
49 state: UniformListState,
50 item_count: usize,
51 append_items: F,
52 padding_top: f32,
53 padding_bottom: f32,
54 get_width_from_item: Option<usize>,
55}
56
57impl<F> UniformList<F>
58where
59 F: Fn(Range<usize>, &mut Vec<ElementBox>, &mut LayoutContext),
60{
61 pub fn new(state: UniformListState, item_count: usize, append_items: F) -> Self {
62 Self {
63 state,
64 item_count,
65 append_items,
66 padding_top: 0.,
67 padding_bottom: 0.,
68 get_width_from_item: None,
69 }
70 }
71
72 pub fn with_width_from_item(mut self, item_ix: Option<usize>) -> Self {
73 self.get_width_from_item = item_ix;
74 self
75 }
76
77 pub fn with_padding_top(mut self, padding: f32) -> Self {
78 self.padding_top = padding;
79 self
80 }
81
82 pub fn with_padding_bottom(mut self, padding: f32) -> Self {
83 self.padding_bottom = padding;
84 self
85 }
86
87 fn scroll(
88 &self,
89 _: Vector2F,
90 mut delta: Vector2F,
91 precise: bool,
92 scroll_max: f32,
93 cx: &mut EventContext,
94 ) -> bool {
95 if !precise {
96 delta *= 20.;
97 }
98
99 let mut state = self.state.0.lock();
100 state.scroll_top = (state.scroll_top - delta.y()).max(0.0).min(scroll_max);
101 cx.notify();
102
103 true
104 }
105
106 fn autoscroll(&mut self, scroll_max: f32, list_height: f32, item_height: f32) {
107 let mut state = self.state.0.lock();
108
109 if let Some(scroll_to) = state.scroll_to.take() {
110 let item_ix;
111 let center;
112 match scroll_to {
113 ScrollTarget::Show(ix) => {
114 item_ix = ix;
115 center = false;
116 }
117 ScrollTarget::Center(ix) => {
118 item_ix = ix;
119 center = true;
120 }
121 }
122
123 let item_top = self.padding_top + item_ix as f32 * item_height;
124 let item_bottom = item_top + item_height;
125 if center {
126 let item_center = item_top + item_height / 2.;
127 state.scroll_top = (item_center - list_height / 2.).max(0.);
128 } else {
129 let scroll_bottom = state.scroll_top + list_height;
130 if item_top < state.scroll_top {
131 state.scroll_top = item_top;
132 } else if item_bottom > scroll_bottom {
133 state.scroll_top = item_bottom - list_height;
134 }
135 }
136 }
137
138 if state.scroll_top > scroll_max {
139 state.scroll_top = scroll_max;
140 }
141 }
142
143 fn scroll_top(&self) -> f32 {
144 self.state.0.lock().scroll_top
145 }
146}
147
148impl<F> Element for UniformList<F>
149where
150 F: Fn(Range<usize>, &mut Vec<ElementBox>, &mut LayoutContext),
151{
152 type LayoutState = LayoutState;
153 type PaintState = ();
154
155 fn layout(
156 &mut self,
157 constraint: SizeConstraint,
158 cx: &mut LayoutContext,
159 ) -> (Vector2F, Self::LayoutState) {
160 if constraint.max.y().is_infinite() {
161 unimplemented!(
162 "UniformList does not support being rendered with an unconstrained height"
163 );
164 }
165 let mut items = Vec::new();
166
167 if self.item_count == 0 {
168 return (
169 constraint.min,
170 LayoutState {
171 item_height: 0.,
172 scroll_max: 0.,
173 items,
174 },
175 );
176 }
177
178 let mut size = constraint.max;
179 let mut item_size;
180 if let Some(sample_item_ix) = self.get_width_from_item {
181 (self.append_items)(sample_item_ix..sample_item_ix + 1, &mut items, cx);
182 let sample_item = items.get_mut(0).unwrap();
183 item_size = sample_item.layout(constraint, cx);
184 size.set_x(item_size.x());
185 } else {
186 (self.append_items)(0..1, &mut items, cx);
187 let first_item = items.first_mut().unwrap();
188 item_size = first_item.layout(
189 SizeConstraint::new(
190 vec2f(constraint.max.x(), 0.0),
191 vec2f(constraint.max.x(), f32::INFINITY),
192 ),
193 cx,
194 );
195 item_size.set_x(size.x());
196 }
197
198 let item_constraint = SizeConstraint {
199 min: item_size,
200 max: vec2f(constraint.max.x(), item_size.y()),
201 };
202 let item_height = item_size.y();
203
204 let scroll_height = self.item_count as f32 * item_height;
205 if scroll_height < size.y() {
206 size.set_y(size.y().min(scroll_height).max(constraint.min.y()));
207 }
208
209 let scroll_height =
210 item_height * self.item_count as f32 + self.padding_top + self.padding_bottom;
211 let scroll_max = (scroll_height - size.y()).max(0.);
212 self.autoscroll(scroll_max, size.y(), item_height);
213
214 let start = cmp::min(
215 ((self.scroll_top() - self.padding_top) / item_height) as usize,
216 self.item_count,
217 );
218 let end = cmp::min(
219 self.item_count,
220 start + (size.y() / item_height).ceil() as usize + 1,
221 );
222 items.clear();
223 (self.append_items)(start..end, &mut items, cx);
224 for item in &mut items {
225 let item_size = item.layout(item_constraint, cx);
226 if item_size.x() > size.x() {
227 size.set_x(item_size.x());
228 }
229 }
230
231 (
232 size,
233 LayoutState {
234 item_height,
235 scroll_max,
236 items,
237 },
238 )
239 }
240
241 fn paint(
242 &mut self,
243 bounds: RectF,
244 visible_bounds: RectF,
245 layout: &mut Self::LayoutState,
246 cx: &mut PaintContext,
247 ) -> Self::PaintState {
248 cx.scene.push_layer(Some(bounds));
249
250 let mut item_origin = bounds.origin()
251 - vec2f(
252 0.,
253 (self.state.scroll_top() - self.padding_top) % layout.item_height,
254 );
255
256 for item in &mut layout.items {
257 item.paint(item_origin, visible_bounds, cx);
258 item_origin += vec2f(0.0, layout.item_height);
259 }
260
261 cx.scene.pop_layer();
262 }
263
264 fn dispatch_event(
265 &mut self,
266 event: &Event,
267 bounds: RectF,
268 layout: &mut Self::LayoutState,
269 _: &mut Self::PaintState,
270 cx: &mut EventContext,
271 ) -> bool {
272 let mut handled = false;
273 for item in &mut layout.items {
274 handled = item.dispatch_event(event, cx) || handled;
275 }
276
277 match event {
278 Event::ScrollWheel {
279 position,
280 delta,
281 precise,
282 } => {
283 if bounds.contains_point(*position) {
284 if self.scroll(*position, *delta, *precise, layout.scroll_max, cx) {
285 handled = true;
286 }
287 }
288 }
289 _ => {}
290 }
291
292 handled
293 }
294
295 fn debug(
296 &self,
297 bounds: RectF,
298 layout: &Self::LayoutState,
299 _: &Self::PaintState,
300 cx: &crate::DebugContext,
301 ) -> json::Value {
302 json!({
303 "type": "UniformList",
304 "bounds": bounds.to_json(),
305 "scroll_max": layout.scroll_max,
306 "item_height": layout.item_height,
307 "items": layout.items.iter().map(|item| item.debug(cx)).collect::<Vec<json::Value>>()
308
309 })
310 }
311}