Skip to main content

compose_rust/ui/
lazy.rs

1//! Lazy lists: the Renderer asks for the window it can show, and only that window is
2//! composed.
3//!
4//! The shape is Compose's: a list takes a builder that says what its items are, in one or
5//! more runs, and composes none of them itself.
6//!
7//! ```ignore
8//! LazyColumn().modifier(Modifier.fill_max_size()).content(|list| {
9//!     list.item(|| { Text("Header"); });
10//!     list.items_keyed(tasks.len(), move |index| ids[index].clone(), move |index| {
11//!         TaskRow(index);
12//!     });
13//! });
14//! ```
15//!
16//! On the wire it is the windowing the `rsx!` lists use: the list declares how many items
17//! there are, the Renderer reports the range it shows, and exactly that range is composed,
18//! each item in a `Box` carrying its key. Scrolling runs the list's items and nothing
19//! above it, because the range is a state only the items read.
20
21#![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
33/// One run of items.
34struct Interval {
35    count: usize,
36    key: Option<Rc<dyn Fn(usize) -> String>>,
37    content: Rc<dyn Fn(usize)>,
38}
39
40/// What a lazy list's builder is handed. Compose's `LazyListScope`.
41#[derive(Default)]
42pub struct LazyListScope {
43    intervals: Vec<Interval>,
44}
45
46impl LazyListScope {
47    /// One item.
48    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    /// `count` items, each composed by `content` with its index in this run. An item's
57    /// key is its position in the whole list, so items that move are rebuilt; use
58    /// [`LazyListScope::items_keyed`] for a list whose items move.
59    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    /// The same, with a stable key per item: an item that moves keeps its node and what
68    /// it remembered.
69    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/// Which list it is.
88#[derive(Clone, Copy, PartialEq, Eq)]
89enum Kind {
90    Column,
91    Row,
92    Grid,
93}
94
95/// A lazy list and its builder.
96pub 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
105/// A vertical list that composes only the items on screen. Compose's `LazyColumn`.
106pub fn LazyColumn() -> LazyList {
107    LazyList::new(Kind::Column)
108}
109
110/// A horizontal list that composes only the items on screen. Compose's `LazyRow`.
111pub fn LazyRow() -> LazyList {
112    LazyList::new(Kind::Row)
113}
114
115/// A grid that composes only the rows on screen. Compose's `LazyVerticalGrid`; say how
116/// wide a column is with `columns` or `min_column_width`.
117pub 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    /// A grid's fixed number of columns. Compose's `GridCells.Fixed`.
139    pub fn columns(mut self, columns: u32) -> Self {
140        self.columns = Some(columns);
141        self
142    }
143
144    /// The narrowest a grid column may be. Compose's `GridCells.Adaptive`.
145    pub fn min_column_width(mut self, dp: f32) -> Self {
146        self.min_column_width = Some(dp);
147        self
148    }
149
150    /// Runs once when this node's size motion comes to rest, with the size it settled
151    /// at in dp. The node needs `Modifier::motion` for its size to move; without it
152    /// nothing is reported. A run interrupted by a newer size is not reported, only
153    /// the one that settles, and under reduced motion it arrives in the frame the
154    /// size changes in.
155    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    /// Composes the list with the items `build` declares.
161    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        // The window the Renderer last asked for. Only the items read it, so a scroll runs
182        // them and nothing else.
183        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/// The items a list's builder declared, compared by identity: a list composed again
229/// declares them again, and a list whose window moved did not.
230#[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
239/// The window of items, as a scope of its own that the range state invalidates.
240fn 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/// One item's content, compared by the closure that composes it and its index.
286#[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
295/// One item, as a scope of its own: a state its content reads runs this item again and
296/// no other.
297fn 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}