1#![allow(non_snake_case)]
22
23use super::widgets::motion_input;
24use super::{Attrs, Modifier, Mods, emit_node, push_modifiers, widget_key};
25use crate::runtime::__private::{RestartGroup, start_restart_group};
26use crate::runtime::composer::{EventCallback, OwnedAttr};
27use crate::runtime::{MutableState, group_guard, key, mutable_state_of, remember};
28use crate::schema::WidgetKind;
29use crate::{MotionFinished, RangeRequest};
30use std::cell::RefCell;
31use std::rc::Rc;
32
33struct Interval {
35 count: usize,
36 key: Option<Rc<dyn Fn(usize) -> String>>,
37 content: Rc<dyn Fn(usize)>,
38}
39
40#[derive(Default)]
42pub struct LazyListScope {
43 intervals: Vec<Interval>,
44}
45
46impl LazyListScope {
47 pub fn item(&mut self, content: impl Fn() + 'static) {
49 self.intervals.push(Interval {
50 count: 1,
51 key: None,
52 content: Rc::new(move |_| content()),
53 });
54 }
55
56 pub fn items(&mut self, count: usize, content: impl Fn(usize) + 'static) {
60 self.intervals.push(Interval {
61 count,
62 key: None,
63 content: Rc::new(content),
64 });
65 }
66
67 pub fn items_keyed(
70 &mut self,
71 count: usize,
72 key: impl Fn(usize) -> String + 'static,
73 content: impl Fn(usize) + 'static,
74 ) {
75 self.intervals.push(Interval {
76 count,
77 key: Some(Rc::new(key)),
78 content: Rc::new(content),
79 });
80 }
81
82 fn total(&self) -> usize {
83 self.intervals.iter().map(|interval| interval.count).sum()
84 }
85}
86
87#[derive(Clone, Copy, PartialEq, Eq)]
89enum Kind {
90 Column,
91 Row,
92 Grid,
93}
94
95pub struct LazyList {
97 kind: Kind,
98 modifier: Modifier,
99 columns: Option<u32>,
100 min_column_width: Option<f32>,
101 on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
102 done: bool,
103}
104
105pub fn LazyColumn() -> LazyList {
107 LazyList::new(Kind::Column)
108}
109
110pub fn LazyRow() -> LazyList {
112 LazyList::new(Kind::Row)
113}
114
115pub fn LazyGrid() -> LazyList {
118 LazyList::new(Kind::Grid)
119}
120
121impl LazyList {
122 fn new(kind: Kind) -> Self {
123 Self {
124 kind,
125 modifier: Modifier::new(),
126 columns: None,
127 min_column_width: None,
128 on_motion_finished: None,
129 done: false,
130 }
131 }
132
133 pub fn modifier(mut self, modifier: Modifier) -> Self {
134 self.modifier = modifier;
135 self
136 }
137
138 pub fn columns(mut self, columns: u32) -> Self {
140 self.columns = Some(columns);
141 self
142 }
143
144 pub fn min_column_width(mut self, dp: f32) -> Self {
146 self.min_column_width = Some(dp);
147 self
148 }
149
150 pub fn on_motion_finished(mut self, handler: impl FnMut(MotionFinished) + 'static) -> Self {
156 self.on_motion_finished = Some(Box::new(handler));
157 self
158 }
159
160 pub fn content(mut self, build: impl FnOnce(&mut LazyListScope)) {
162 self.done = true;
163 let mut scope = LazyListScope::default();
164 build(&mut scope);
165 self.compose(scope);
166 }
167
168 fn compose(&mut self, scope: LazyListScope) {
169 let (kind, modifier, columns, min_column_width) = (
170 self.kind,
171 std::mem::take(&mut self.modifier),
172 self.columns,
173 self.min_column_width,
174 );
175 let (widget, name) = match kind {
176 Kind::Column => (WidgetKind::LazyColumn, "compose_rust::ui::LazyColumn"),
177 Kind::Row => (WidgetKind::LazyRow, "compose_rust::ui::LazyRow"),
178 Kind::Grid => (WidgetKind::LazyGrid, "compose_rust::ui::LazyGrid"),
179 };
180 let _group = group_guard(widget_key(name));
181 let range = remember(|| mutable_state_of((0_usize, 0_usize)));
184 let total = scope.total();
185 let request = range;
186 let listener = EventCallback::Range(Rc::new(RefCell::new(move |asked: RangeRequest| {
187 request.set((asked.start(), asked.count()));
188 })));
189 let intervals = Rc::new(scope.intervals);
190 let mut listeners = vec![("onrangerequest", listener)];
191 motion_input(self.on_motion_finished.take(), &mut listeners);
192 emit_node(
193 widget,
194 |attrs: &mut Attrs| {
195 push_modifiers(&modifier, Mods::Standard, attrs);
196 attrs.push(("item_count", OwnedAttr::Int(total as i64)));
197 if kind == Kind::Grid {
198 attrs.push((
199 "columns",
200 columns.map_or(OwnedAttr::None, |count| OwnedAttr::Int(i64::from(count))),
201 ));
202 attrs.push((
203 "min_column_width",
204 min_column_width
205 .map_or(OwnedAttr::None, |dp| OwnedAttr::Float(f64::from(dp))),
206 ));
207 }
208 },
209 listeners,
210 || Items(range, intervals),
211 );
212 }
213}
214
215impl Drop for LazyList {
216 fn drop(&mut self) {
217 if !self.done && !std::thread::panicking() {
218 self.done = true;
219 self.compose(LazyListScope::default());
220 }
221 }
222}
223
224const ITEMS: u64 = widget_key("compose_rust::ui::LazyList::items");
225const ITEM: u64 = widget_key("compose_rust::ui::LazyList::item");
226const ITEM_BOX: u64 = widget_key("compose_rust::ui::LazyList::item_box");
227
228#[derive(Clone)]
231struct SameIntervals(Rc<Vec<Interval>>);
232
233impl PartialEq for SameIntervals {
234 fn eq(&self, other: &Self) -> bool {
235 Rc::ptr_eq(&self.0, &other.0)
236 }
237}
238
239fn Items(range: MutableState<(usize, usize)>, intervals: Rc<Vec<Interval>>) {
241 let scope: RestartGroup = start_restart_group(ITEMS);
242 let fresh = scope.param_changed(0, &SameIntervals(Rc::clone(&intervals)));
243 if !scope.must_run() && !fresh {
244 scope.skip();
245 return;
246 }
247 {
248 let (range, intervals) = (range, Rc::clone(&intervals));
249 scope.set_restart(move || Items(range, Rc::clone(&intervals)));
250 }
251 let total: usize = intervals.iter().map(|interval| interval.count).sum();
252 let (start, count) = range.get();
253 let first = start.min(total);
254 let last = first.saturating_add(count).min(total);
255 for index in first..last {
256 let mut offset = index;
257 let Some(interval) = intervals.iter().find(|interval| {
258 if offset < interval.count {
259 true
260 } else {
261 offset -= interval.count;
262 false
263 }
264 }) else {
265 continue;
266 };
267 let item_key = interval
268 .key
269 .as_ref()
270 .map_or_else(|| index.to_string(), |key| key(offset));
271 let content = Rc::clone(&interval.content);
272 let local = offset;
273 key(item_key.clone(), || {
274 let _group = group_guard(ITEM_BOX);
275 emit_node(
276 WidgetKind::Box,
277 |attrs: &mut Attrs| attrs.push(("item_key", OwnedAttr::Text(item_key))),
278 Vec::new(),
279 || Item(content, local),
280 );
281 });
282 }
283}
284
285#[derive(Clone)]
287struct SameItem(Rc<dyn Fn(usize)>, usize);
288
289impl PartialEq for SameItem {
290 fn eq(&self, other: &Self) -> bool {
291 Rc::ptr_eq(&self.0, &other.0) && self.1 == other.1
292 }
293}
294
295fn Item(content: Rc<dyn Fn(usize)>, index: usize) {
298 let scope: RestartGroup = start_restart_group(ITEM);
299 let changed = scope.param_changed(0, &SameItem(Rc::clone(&content), index));
300 if !scope.must_run() && !changed {
301 scope.skip();
302 return;
303 }
304 {
305 let content = Rc::clone(&content);
306 scope.set_restart(move || Item(Rc::clone(&content), index));
307 }
308 content(index);
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 #[test]
316 fn fr39_the_items_of_several_runs_are_one_index_space() {
317 let mut scope = LazyListScope::default();
318 scope.item(|| {});
319 scope.items(3, |_| {});
320 scope.items_keyed(2, |index| format!("k{index}"), |_| {});
321 assert_eq!(scope.total(), 6);
322 }
323}