Skip to main content

cosmic_applet_avestruz/views/components/
virtual_list.rs

1// SPDX-License-Identifier: MIT
2
3//! A virtual list whose rows are as tall as their content.
4//!
5//! A feed is long, grows at both ends, and no two notes are the same height.
6//! iced's virtual [`List`](cosmic::iced::widget::list::List) only renders the
7//! rows in view, but to know where they sit it builds and lays out **every**
8//! item whenever its content is new, and draws nothing until it has.
9//!
10//! [`VirtualList`] never measures a row before it is in view. A row that has
11//! been shown has its real height; one that hasn't has the height the caller
12//! estimates for its item. It only ever builds the rows in the viewport, so
13//! showing a feed costs the same whatever its length.
14//!
15//! ```mermaid
16//! flowchart TB
17//!     subgraph list["A list of 500 notes, scrolled some way down"]
18//!         above["Rows above: measured when they went by. Not built"]
19//!         subgraph viewport["The viewport"]
20//!             r1["A row: built, laid out, measured"]
21//!             r2["A row: built, laid out, measured"]
22//!             r3["A row: built, laid out, measured"]
23//!         end
24//!         below["Rows below: never shown. Each as tall as its estimate. Not built"]
25//!         above --- r1 --- r2 --- r3 --- below
26//!     end
27//!     heights[("RowHeights: by note id, in the model")]
28//!     r2 -- "what each row measured" --> heights
29//!     heights -- "where each row starts" --> above
30//! ```
31//!
32//! Each frame, the list works out where every row starts from the heights
33//! it knows and the estimates for the rest (a sum, with no widget built),
34//! finds the first row that reaches into the viewport, and builds rows
35//! from there until one starts below it. Each row built is measured, and
36//! what it measured is kept. If a row turned out another height than it
37//! was laid out with, the list is laid out once more.
38//!
39//! Scrolled from the top, everything above the viewport has been measured, so
40//! what is on screen never moves: only the scrollbar's idea of the total
41//! changes as estimates below turn into measurements. After a jump over rows
42//! never shown (dragging the scrollbar), the rows above are still estimates;
43//! scrolling back up into them moves what is on screen by however far each
44//! estimate was off, so the closer the estimate, the steadier the list.
45//!
46//! The estimate has to depend on the item and on how wide the list is, and
47//! on nothing else. Assuming the average of the
48//! rows measured so far looks better and is worse: every newly measured row
49//! would move the average, and with it every unmeasured row above the
50//! viewport, so after a jump the list would land on different rows frame
51//! after frame.
52//!
53//! The list can say when it has been scrolled near its end, which is when a
54//! feed fetches its next page. It says so in answer to any event but a redraw
55//! (the pointer moving, a wheel turning), never while the window is being
56//! redrawn: a message published during a redraw makes the
57//! runtime take the window's size afresh in the middle of the frame, and if
58//! the popup is being resized just then (as it is while it opens), the frame
59//! is presented into a buffer of the old size and `iced_tiny_skia` panics.
60//! That rules out the scrollable's own `on_scroll`, which reports during
61//! redraws, and again each time a measured row changes the list's height.
62//!
63//! A row that is another height at its reader's asking (a long note
64//! shown in full, or cut again) is the one row measured before it is in
65//! view: its list is told ([`RowHeights::measure_anew`]), and measures it
66//! in the layout that follows, so that the list is the right length at
67//! once.
68//!
69//! Heights are remembered by row *key*, not index, in a [`RowHeights`] the
70//! caller owns. Rows added at the front leave the rest measured, and the
71//! measurements outlive the widget tree: a popup that is closed and opened
72//! again lays its list out exactly as it was.
73//!
74//! Where the list is scrolled to outlives the widget tree the same way, but
75//! is not the list's to keep: its scroller may hold more than the list. See
76//! [`ScrollPosition`](super::ScrollPosition).
77
78use std::cell::RefCell;
79use std::collections::{HashMap, HashSet};
80use std::hash::Hash;
81
82use cosmic::iced::core::layout;
83use cosmic::iced::core::mouse;
84use cosmic::iced::core::overlay;
85use cosmic::iced::core::renderer;
86use cosmic::iced::core::widget::Operation;
87use cosmic::iced::core::widget::tree::{self, Tree};
88use cosmic::iced::core::window;
89use cosmic::iced::core::{Clipboard, Element, Event, Layout, Length, Point, Rectangle, Shell, Size, Vector, Widget};
90
91/// How far two heights may differ and still be the same height.
92const SAME_HEIGHT: f32 = 0.01;
93
94/// The measured heights of a list's rows, by row key, at one list width.
95///
96/// Owned by whoever owns the list's items, and lent to the [`VirtualList`]
97/// built for each frame, which fills it in as rows come into view.
98pub struct RowHeights<K> {
99    measured: RefCell<Measured<K>>,
100}
101
102struct Measured<K> {
103    /// The list width the heights were measured at. Text wraps differently
104    /// at another width, so the heights are only good for this one.
105    width: f32,
106    heights: HashMap<K, f32>,
107    /// The rows to measure before the list is next laid out, in view or
108    /// not: see [`RowHeights::measure_anew`].
109    anew: HashSet<K>,
110}
111
112impl<K> Default for RowHeights<K> {
113    fn default() -> Self {
114        Self { measured: RefCell::new(Measured { width: 0.0, heights: HashMap::new(), anew: HashSet::new() }) }
115    }
116}
117
118impl<K: Eq + Hash + Clone> RowHeights<K> {
119    /// How many rows have been measured.
120    pub fn len(&self) -> usize {
121        self.measured.borrow().heights.len()
122    }
123
124    pub fn is_empty(&self) -> bool {
125        self.len() == 0
126    }
127
128    /// The measured height of the row `key`, if it has been in view.
129    pub fn get(&self, key: &K) -> Option<f32> {
130        self.measured.borrow().heights.get(key).copied()
131    }
132
133    /// How tall the rows of `items` are together: each its measured height,
134    /// or what `estimate` says of the item until it has one, at the width
135    /// the list was last laid out at (none, before it ever was). With the
136    /// items before a row, that is where the row starts.
137    pub fn total<T>(&self, items: &[T], key: impl Fn(&T) -> K, estimate: impl Fn(&T, f32) -> f32) -> f32 {
138        let width = self.measured.borrow().width;
139        items.iter().map(|item| self.get(&key(item)).unwrap_or_else(|| estimate(item, width).max(0.0))).sum()
140    }
141
142    /// Where each row of `items` starts, from the top of the list: each
143    /// after the heights of those before it, measured or estimated as in
144    /// [`Self::total`]. What a list is scrolled to to have a row at the
145    /// top of what is in view.
146    pub fn starts<T>(&self, items: &[T], key: impl Fn(&T) -> K, estimate: impl Fn(&T, f32) -> f32) -> Vec<f32> {
147        let width = self.measured.borrow().width;
148        let mut start = 0.0;
149        items
150            .iter()
151            .map(|item| {
152                let here = start;
153                start += self.get(&key(item)).unwrap_or_else(|| estimate(item, width).max(0.0));
154                here
155            })
156            .collect()
157    }
158
159    /// Forget how tall the row `key` measured, and have it measured before
160    /// the list is next laid out, whether it is in view or not: the row is
161    /// about to be another height, at its reader's asking.
162    ///
163    /// A row that only comes to be another height is found out when it
164    /// is next in view, and the list is laid out again then. That is one
165    /// layout too late for what follows such a change at once, as
166    /// scrolling the list to a place counted from its new length.
167    pub fn measure_anew(&self, key: K) {
168        let mut measured = self.measured.borrow_mut();
169        measured.heights.remove(&key);
170        measured.anew.insert(key);
171    }
172
173    /// The rows to measure before the list is laid out, which are then no
174    /// longer waiting to be.
175    fn take_anew(&self) -> HashSet<K> {
176        std::mem::take(&mut self.measured.borrow_mut().anew)
177    }
178
179    /// Lay out at `width` from now on, forgetting heights measured at another.
180    fn set_width(&self, width: f32) {
181        let mut measured = self.measured.borrow_mut();
182        if measured.width != width {
183            measured.width = width;
184            measured.heights.clear();
185        }
186    }
187
188    /// Remember that the row `key` is `height` tall. Returns whether that is
189    /// news.
190    fn record(&self, key: &K, height: f32) -> bool {
191        let mut measured = self.measured.borrow_mut();
192        match measured.heights.get_mut(key) {
193            Some(known) if (*known - height).abs() <= SAME_HEIGHT => false,
194            Some(known) => {
195                *known = height;
196                true
197            }
198            None => {
199                measured.heights.insert(key.clone(), height);
200                true
201            }
202        }
203    }
204}
205
206/// How tall the row of an item is assumed to be until it has been in view,
207/// in a list as wide as the second argument.
208type Estimate<'a, T> = Box<dyn Fn(&T, f32) -> f32 + 'a>;
209
210/// A virtual list of rows of any height. See the [module docs](self).
211pub struct VirtualList<'a, T, K, Message, Theme, Renderer> {
212    items: &'a [T],
213    heights: &'a RowHeights<K>,
214    key: Box<dyn Fn(&T) -> K + 'a>,
215    view_item: Box<dyn Fn(usize, &'a T) -> Element<'a, Message, Theme, Renderer> + 'a>,
216    estimate: Estimate<'a, T>,
217    /// The rows in view, in the same order as [`State::rows`]. Rebuilt from
218    /// `view_item` the first time this widget instance handles an event,
219    /// because the app builds a new instance on every `view()`.
220    visible: Vec<Element<'a, Message, Theme, Renderer>>,
221    /// The viewport, and the list's own top, that `visible` was built for.
222    synced: Option<(Rectangle, f32)>,
223    /// How close to the list's end the viewport has to come, and what to
224    /// publish when it does.
225    near_end: Option<(f32, Message)>,
226}
227
228impl<'a, T, K, Message, Theme, Renderer> VirtualList<'a, T, K, Message, Theme, Renderer> {
229    /// A list of `items`, each built by `view_item(index, item)` and known,
230    /// across frames and reorderings, by `key(item)`. Until a row has been in
231    /// view it is assumed to be `estimate(item, width)` tall, in a list
232    /// `width` wide.
233    pub fn new(
234        items: &'a [T],
235        heights: &'a RowHeights<K>,
236        key: impl Fn(&T) -> K + 'a,
237        estimate: impl Fn(&T, f32) -> f32 + 'a,
238        view_item: impl Fn(usize, &'a T) -> Element<'a, Message, Theme, Renderer> + 'a,
239    ) -> Self {
240        Self {
241            items,
242            heights,
243            key: Box::new(key),
244            estimate: Box::new(estimate),
245            view_item: Box::new(view_item),
246            visible: Vec::new(),
247            synced: None,
248            near_end: None,
249        }
250    }
251
252    /// Publish `message` when the viewport comes within `distance` of the
253    /// list's end: once for each place the list is scrolled to, so scrolling
254    /// on asks again, and staying put doesn't.
255    pub fn on_near_end(mut self, distance: f32, message: Message) -> Self {
256        self.near_end = Some((distance, message));
257        self
258    }
259}
260
261/// One row in view: which item it shows, where it sits, and its widget state.
262struct Row<K> {
263    key: K,
264    node: layout::Node,
265    tree: Tree,
266}
267
268struct State<K> {
269    /// The limits rows are laid out with: the list's width, and any height.
270    limits: layout::Limits,
271    /// Where each row starts, measured or assumed, and after the last one,
272    /// where the list ends. Rebuilt by every layout.
273    offsets: Vec<f32>,
274    /// The rows in view, top to bottom.
275    rows: Vec<Row<K>>,
276    /// The list length and viewport position at which nearing the end was
277    /// last published.
278    near_end_told: Option<(usize, f32)>,
279}
280
281impl<'a, T, K, Message, Theme, Renderer> VirtualList<'a, T, K, Message, Theme, Renderer>
282where
283    K: Eq + Hash + Clone,
284    Renderer: renderer::Renderer,
285{
286    /// Make `self.visible` and `state.rows` hold exactly the rows in
287    /// `viewport`, each built for this frame, laid out, and placed under the
288    /// one before it. Returns whether any of them turned out to be a different
289    /// height than the list was laid out with.
290    ///
291    /// A row that was already in view keeps its widget state (hover, press),
292    /// reconciled against the freshly built row.
293    fn sync_visible(&mut self, state: &mut State<K>, layout: Layout<'_>, renderer: &Renderer, viewport: &Rectangle) -> bool {
294        let top = layout.position().y;
295        if self.synced == Some((*viewport, top)) {
296            return false;
297        }
298        self.synced = Some((*viewport, top));
299
300        let view_top = viewport.y - top;
301        let view_bottom = view_top + viewport.height;
302
303        // The last row that starts at or above the top of the viewport.
304        let starts = state.offsets.get(..self.items.len()).unwrap_or_default();
305        let first = starts.partition_point(|&start| start <= view_top).saturating_sub(1);
306        let mut y = starts.get(first).copied().unwrap_or(0.0);
307
308        let mut previous = std::mem::take(&mut state.rows);
309        self.visible.clear();
310        let mut changed = false;
311        for (index, item) in self.items.iter().enumerate().skip(first) {
312            if y >= view_bottom {
313                break;
314            }
315            let key = (self.key)(item);
316            let mut element = (self.view_item)(index, item);
317            let mut tree = match previous.iter().position(|row| row.key == key) {
318                Some(at) => {
319                    let mut tree = previous.swap_remove(at).tree;
320                    tree.diff(element.as_widget_mut());
321                    tree
322                }
323                None => Tree::new(element.as_widget()),
324            };
325            let node = element.as_widget_mut().layout(&mut tree, renderer, &state.limits).move_to((0.0, y));
326            let height = node.size().height;
327            changed |= self.heights.record(&key, height);
328            y += height;
329            state.rows.push(Row { key, node, tree });
330            self.visible.push(element);
331        }
332        changed
333    }
334}
335
336impl<'a, T, K, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for VirtualList<'a, T, K, Message, Theme, Renderer>
337where
338    K: Eq + Hash + Clone + 'static,
339    Message: Clone,
340    Renderer: renderer::Renderer,
341{
342    fn tag(&self) -> tree::Tag {
343        tree::Tag::of::<State<K>>()
344    }
345
346    fn state(&self) -> tree::State {
347        tree::State::new(State::<K> { limits: layout::Limits::NONE, offsets: Vec::new(), rows: Vec::new(), near_end_told: None })
348    }
349
350    fn size(&self) -> Size<Length> {
351        Size::new(Length::Fill, Length::Shrink)
352    }
353
354    fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
355        let state = tree.state.downcast_mut::<State<K>>();
356
357        // Rows are as wide as the list and as tall as they like.
358        let width = limits.max().width;
359        let row_limits = layout::Limits::new(Size::ZERO, Size::new(width, f32::INFINITY));
360        if state.limits != row_limits {
361            state.limits = row_limits;
362            state.rows.clear();
363            self.visible.clear();
364        }
365        self.heights.set_width(width);
366
367        // The rows whose height was asked to be measured anew: each is
368        // built and laid out here, once, so that the list is as long as
369        // it will be from this layout on.
370        let anew = self.heights.take_anew();
371        if !anew.is_empty() {
372            for (index, item) in self.items.iter().enumerate() {
373                let key = (self.key)(item);
374                if anew.contains(&key) {
375                    let mut element = (self.view_item)(index, item);
376                    let mut row = Tree::new(element.as_widget());
377                    let height = element.as_widget_mut().layout(&mut row, renderer, &row_limits).size().height;
378                    self.heights.record(&key, height);
379                }
380            }
381        }
382
383        // The rows in view stay as they are until the next event places them
384        // again: a layout asked for mid-frame is followed by a draw.
385        self.synced = None;
386
387        state.offsets.clear();
388        state.offsets.reserve(self.items.len() + 1);
389        let mut y = 0.0;
390        for item in self.items {
391            state.offsets.push(y);
392            y += self.heights.get(&(self.key)(item)).unwrap_or_else(|| (self.estimate)(item, width).max(0.0));
393        }
394        state.offsets.push(y);
395
396        layout::Node::new(limits.resolve(Length::Fill, Length::Shrink, Size::new(width, y)))
397    }
398
399    fn update(
400        &mut self,
401        tree: &mut Tree,
402        event: &Event,
403        layout: Layout<'_>,
404        cursor: mouse::Cursor,
405        renderer: &Renderer,
406        clipboard: &mut dyn Clipboard,
407        shell: &mut Shell<'_, Message>,
408        viewport: &Rectangle,
409    ) {
410        let state = tree.state.downcast_mut::<State<K>>();
411        if self.sync_visible(state, layout, renderer, viewport) {
412            // The list is not the height it was laid out with. The rows in
413            // view are already where they belong; the total, and the rows
414            // below, follow in the next layout.
415            shell.invalidate_layout();
416            shell.request_redraw();
417        }
418
419        let offset = layout.position() - Point::ORIGIN;
420        for (element, row) in self.visible.iter_mut().zip(&mut state.rows) {
421            element.as_widget_mut().update(
422                &mut row.tree,
423                event,
424                Layout::with_offset(offset, &row.node),
425                cursor,
426                renderer,
427                clipboard,
428                shell,
429                viewport,
430            );
431        }
432
433        // Never in answer to a redraw: see the module docs for why.
434        if let Some((distance, message)) = &self.near_end
435            && !matches!(event, Event::Window(window::Event::RedrawRequested(_)))
436            && !self.items.is_empty()
437        {
438            let end = state.offsets.last().copied().unwrap_or(0.0);
439            let view_bottom = viewport.y + viewport.height - layout.position().y;
440            let here = (self.items.len(), viewport.y);
441            if end - view_bottom <= *distance && state.near_end_told != Some(here) {
442                state.near_end_told = Some(here);
443                shell.publish(message.clone());
444            }
445        }
446    }
447
448    fn draw(
449        &self,
450        tree: &Tree,
451        renderer: &mut Renderer,
452        theme: &Theme,
453        style: &renderer::Style,
454        layout: Layout<'_>,
455        cursor: mouse::Cursor,
456        viewport: &Rectangle,
457    ) {
458        let state = tree.state.downcast_ref::<State<K>>();
459        let offset = layout.position() - Point::ORIGIN;
460        for (element, row) in self.visible.iter().zip(&state.rows) {
461            element.as_widget().draw(&row.tree, renderer, theme, style, Layout::with_offset(offset, &row.node), cursor, viewport);
462        }
463    }
464
465    fn mouse_interaction(
466        &self,
467        tree: &Tree,
468        layout: Layout<'_>,
469        cursor: mouse::Cursor,
470        viewport: &Rectangle,
471        renderer: &Renderer,
472    ) -> mouse::Interaction {
473        let state = tree.state.downcast_ref::<State<K>>();
474        let offset = layout.position() - Point::ORIGIN;
475        self.visible
476            .iter()
477            .zip(&state.rows)
478            .map(|(element, row)| {
479                element.as_widget().mouse_interaction(
480                    &row.tree,
481                    Layout::with_offset(offset, &row.node),
482                    cursor,
483                    viewport,
484                    renderer,
485                )
486            })
487            .max()
488            .unwrap_or_default()
489    }
490
491    fn operate(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) {
492        let state = tree.state.downcast_mut::<State<K>>();
493        let offset = layout.position() - Point::ORIGIN;
494        for (element, row) in self.visible.iter_mut().zip(&mut state.rows) {
495            element.as_widget_mut().operate(&mut row.tree, Layout::with_offset(offset, &row.node), renderer, operation);
496        }
497    }
498
499    fn overlay<'b>(
500        &'b mut self,
501        tree: &'b mut Tree,
502        layout: Layout<'_>,
503        renderer: &Renderer,
504        viewport: &Rectangle,
505        translation: Vector,
506    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
507        let state = tree.state.downcast_mut::<State<K>>();
508        let offset = layout.position() - Point::ORIGIN;
509        let children: Vec<_> = self
510            .visible
511            .iter_mut()
512            .zip(&mut state.rows)
513            .filter_map(|(element, row)| {
514                element.as_widget_mut().overlay(
515                    &mut row.tree,
516                    Layout::with_offset(offset, &row.node),
517                    renderer,
518                    viewport,
519                    translation,
520                )
521            })
522            .collect();
523        (!children.is_empty()).then(|| overlay::Group::with_children(children).overlay())
524    }
525}
526
527impl<'a, T, K, Message, Theme, Renderer> From<VirtualList<'a, T, K, Message, Theme, Renderer>>
528    for Element<'a, Message, Theme, Renderer>
529where
530    T: 'a,
531    K: Eq + Hash + Clone + 'static,
532    Message: Clone + 'a,
533    Theme: 'a,
534    Renderer: renderer::Renderer + 'a,
535{
536    fn from(list: VirtualList<'a, T, K, Message, Theme, Renderer>) -> Self {
537        Element::new(list)
538    }
539}
540
541#[cfg(test)]
542mod tests {
543    use super::{RowHeights, VirtualList};
544    use cosmic::iced::core::widget::{Tree, tree};
545    use cosmic::iced::core::{
546        Element, Event, Layout, Length, Point, Rectangle, Shell, Size, Widget, clipboard, layout, mouse, renderer, window,
547    };
548    use std::cell::RefCell;
549    use std::rc::Rc;
550
551    const WIDTH: f32 = 300.0;
552    const VIEW: f32 = 300.0;
553    /// What every row is assumed to be until it has been in view.
554    const ESTIMATE: f32 = 50.0;
555
556    /// A list item: its key, and how tall its row is.
557    type Item = (u32, f32);
558
559    /// A row of known height whose tree state is its `marker`, recording
560    /// where it was drawn. The null renderer runs it without a display.
561    struct Probe {
562        height: f32,
563        marker: u32,
564        draws: Rc<RefCell<Vec<(u32, Rectangle)>>>,
565    }
566
567    impl<Msg, Theme, Renderer: renderer::Renderer> Widget<Msg, Theme, Renderer> for Probe {
568        fn size(&self) -> Size<Length> {
569            Size::new(Length::Fill, Length::Fixed(self.height))
570        }
571
572        fn tag(&self) -> tree::Tag {
573            tree::Tag::of::<u32>()
574        }
575
576        fn state(&self) -> tree::State {
577            tree::State::new(self.marker)
578        }
579
580        fn layout(&mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
581            layout::Node::new(Size::new(limits.max().width, self.height))
582        }
583
584        fn draw(
585            &self,
586            tree: &Tree,
587            _renderer: &mut Renderer,
588            _theme: &Theme,
589            _style: &renderer::Style,
590            layout: Layout<'_>,
591            _cursor: mouse::Cursor,
592            _viewport: &Rectangle,
593        ) {
594            self.draws.borrow_mut().push((*tree.state.downcast_ref::<u32>(), layout.bounds()));
595        }
596    }
597
598    type Headless<'a> = Element<'a, (), (), ()>;
599
600    /// Records each row built (by index) and each row drawn (by the marker
601    /// its *state* holds, and where).
602    #[derive(Default)]
603    struct Log {
604        built: Rc<RefCell<Vec<usize>>>,
605        draws: Rc<RefCell<Vec<(u32, Rectangle)>>>,
606    }
607
608    /// A list whose rows carry `marker_base + key` as their state.
609    fn list<'a>(items: &'a [Item], heights: &'a RowHeights<u32>, marker_base: u32, log: &Log) -> Headless<'a> {
610        let (built, draws) = (log.built.clone(), log.draws.clone());
611        VirtualList::new(
612            items,
613            heights,
614            |item: &Item| item.0,
615            |_, _| ESTIMATE,
616            move |index, (key, height)| {
617                built.borrow_mut().push(index);
618                Headless::new(Probe { height: *height, marker: marker_base + key, draws: draws.clone() })
619            },
620        )
621        .into()
622    }
623
624    fn lay_out(element: &mut Headless<'_>, tree: &mut Tree, width: f32) -> layout::Node {
625        let limits = layout::Limits::new(Size::ZERO, Size::new(width, f32::INFINITY));
626        element.as_widget_mut().layout(tree, &(), &limits)
627    }
628
629    /// One frame scrolled to `scroll_y`, as the runtime runs it: layout, a
630    /// redraw event, layout again for as long as the list asks, then draw.
631    /// Returns the list's laid-out height.
632    fn frame(element: &mut Headless<'_>, tree: &mut Tree, scroll_y: f32, log: &Log) -> f32 {
633        let viewport = Rectangle::new(Point::new(0.0, scroll_y), Size::new(WIDTH, VIEW));
634        let mut node = lay_out(element, tree, WIDTH);
635        for _ in 0..16 {
636            let mut messages = Vec::new();
637            let mut shell = Shell::new(&mut messages);
638            element.as_widget_mut().update(
639                tree,
640                &Event::Window(window::Event::RedrawRequested(std::time::Instant::now())),
641                Layout::new(&node),
642                mouse::Cursor::Unavailable,
643                &(),
644                &mut clipboard::Null,
645                &mut shell,
646                &viewport,
647            );
648            if !shell.is_layout_invalid() {
649                break;
650            }
651            node = lay_out(element, tree, WIDTH);
652        }
653        log.draws.borrow_mut().clear();
654        element.as_widget().draw(
655            tree,
656            &mut (),
657            &(),
658            &renderer::Style::default(),
659            Layout::new(&node),
660            mouse::Cursor::Unavailable,
661            &viewport,
662        );
663        node.size().height
664    }
665
666    /// Where each drawn row starts, top to bottom.
667    fn drawn_at(log: &Log) -> Vec<f32> {
668        log.draws.borrow().iter().map(|(_, bounds)| bounds.y).collect()
669    }
670
671    /// The markers of the drawn rows, top to bottom.
672    fn drawn_markers(log: &Log) -> Vec<u32> {
673        log.draws.borrow().iter().map(|(marker, _)| *marker).collect()
674    }
675
676    /// `count` items keyed 0.., with heights cycling through `heights`.
677    fn items(count: u32, heights: &[f32]) -> Vec<Item> {
678        (0..count).map(|key| (key, heights[key as usize % heights.len()])).collect()
679    }
680
681    #[test]
682    fn rows_sit_under_one_another_at_their_own_heights() {
683        let items = items(100, &[40.0, 100.0, 60.0, 30.0, 200.0]);
684        let (heights, log) = (RowHeights::default(), Log::default());
685        let mut element = list(&items, &heights, 0, &log);
686        let mut tree = Tree::new(element.as_widget());
687
688        frame(&mut element, &mut tree, 0.0, &log);
689
690        // 40 + 100 + 60 + 30 = 230: the fifth row starts inside the 300px
691        // viewport and the sixth would start at 430, outside it.
692        assert_eq!(drawn_at(&log), [0.0, 40.0, 140.0, 200.0, 230.0]);
693        assert_eq!(heights.len(), 5, "only the rows in view were measured");
694        assert!(log.built.borrow().iter().all(|index| *index < 5), "only the rows in view were built");
695    }
696
697    #[test]
698    fn a_row_asked_to_be_measured_anew_is_measured_by_the_next_layout_in_view_or_not() {
699        let mut items = items(100, &[40.0]);
700        let (heights, log) = (RowHeights::default(), Log::default());
701        {
702            let mut element = list(&items, &heights, 0, &log);
703            let mut tree = Tree::new(element.as_widget());
704            // Eight rows are in view and measured: 320 in all, and 92 at
705            // their estimate.
706            assert_eq!(frame(&mut element, &mut tree, 0.0, &log), 8.0 * 40.0 + 92.0 * ESTIMATE);
707        }
708
709        // One in view grows and one far out of view shrinks, at their
710        // reader's asking: the list is told of both.
711        items[2].1 = 400.0;
712        items[90].1 = 10.0;
713        heights.measure_anew(2);
714        heights.measure_anew(90);
715        log.built.borrow_mut().clear();
716        let mut element = list(&items, &heights, 0, &log);
717        let mut tree = Tree::new(element.as_widget());
718
719        // The first layout has them both, with no event in between, and
720        // built no other row for it.
721        let height = lay_out(&mut element, &mut tree, WIDTH).size().height;
722        assert_eq!(height, 7.0 * 40.0 + 400.0 + 10.0 + 91.0 * ESTIMATE);
723        assert_eq!(*log.built.borrow(), [2, 90]);
724        assert_eq!((heights.get(&2), heights.get(&90)), (Some(400.0), Some(10.0)));
725
726        // Once: the next layout builds nothing.
727        log.built.borrow_mut().clear();
728        assert_eq!(lay_out(&mut element, &mut tree, WIDTH).size().height, height);
729        assert!(log.built.borrow().is_empty());
730
731        // A row that is no longer in the list is not waited for.
732        heights.measure_anew(1_000);
733        assert_eq!(lay_out(&mut element, &mut tree, WIDTH).size().height, height);
734        assert_eq!(heights.get(&1_000), None);
735    }
736
737    #[test]
738    fn rows_not_yet_seen_are_as_tall_as_their_estimate() {
739        let items = items(1_000, &[40.0, 100.0, 60.0, 30.0, 200.0]);
740        let (heights, log) = (RowHeights::default(), Log::default());
741        let mut element = list(&items, &heights, 0, &log);
742        let mut tree = Tree::new(element.as_widget());
743
744        // Before anything is measured, every row is its estimate.
745        assert_eq!(lay_out(&mut element, &mut tree, WIDTH).size().height, 1_000.0 * ESTIMATE);
746
747        // Five rows measured, 430px in all; the other 995 are still estimates.
748        let height = frame(&mut element, &mut tree, 0.0, &log);
749        assert_eq!(height, 430.0 + 995.0 * ESTIMATE);
750    }
751
752    #[test]
753    fn scrolling_down_never_moves_what_is_on_screen() {
754        let cycle = [40.0, 100.0, 60.0, 30.0, 200.0];
755        let items = items(200, &cycle);
756        let (heights, log) = (RowHeights::default(), Log::default());
757        let mut element = list(&items, &heights, 0, &log);
758        let mut tree = Tree::new(element.as_widget());
759
760        // Scroll down a little at a time, as a wheel does, past 60 rows.
761        let mut scroll = 0.0;
762        while scroll < 5_000.0 {
763            frame(&mut element, &mut tree, scroll, &log);
764            // Every drawn row is exactly where the rows above it put it.
765            for (marker, bounds) in log.draws.borrow().iter() {
766                let above: f32 = items.iter().take(*marker as usize).map(|(_, height)| height).sum();
767                assert_eq!(bounds.y, above, "row {marker} at scroll {scroll}");
768            }
769            scroll += 120.0;
770        }
771    }
772
773    #[test]
774    fn jumping_far_builds_only_the_rows_that_land_in_view() {
775        let items = items(5_000, &[40.0, 100.0, 60.0, 30.0, 200.0]);
776        let (heights, log) = (RowHeights::default(), Log::default());
777        let mut element = list(&items, &heights, 0, &log);
778        let mut tree = Tree::new(element.as_widget());
779        frame(&mut element, &mut tree, 0.0, &log);
780        log.built.borrow_mut().clear();
781
782        // Past 4000 rows that were never shown, so are 50px each: row 4000
783        // starts at 200,180 (the five measured rows are 430px, not 250px).
784        frame(&mut element, &mut tree, 200_200.0, &log);
785
786        let built = log.built.borrow();
787        let (first, last) = (built.iter().min().unwrap(), built.iter().max().unwrap());
788        assert_eq!(*first, 4_000, "the row the estimates put at the top of the viewport");
789        assert!(last - first < 8, "a viewport's worth of rows, not a list's: {first}..={last}");
790        // The rows drawn cover the viewport without a gap.
791        let draws = log.draws.borrow();
792        assert_eq!(draws.first().unwrap().1.y, 200_180.0);
793        for pair in draws.windows(2) {
794            assert_eq!(pair[0].1.y + pair[0].1.height, pair[1].1.y);
795        }
796        let last_drawn = draws.last().unwrap().1;
797        assert!(last_drawn.y + last_drawn.height >= 200_200.0 + VIEW);
798    }
799
800    #[test]
801    fn a_jump_lands_on_the_same_rows_however_many_frames_follow() {
802        let items = items(5_000, &[40.0, 100.0, 60.0, 30.0, 200.0]);
803        let (heights, log) = (RowHeights::default(), Log::default());
804        let mut element = list(&items, &heights, 0, &log);
805        let mut tree = Tree::new(element.as_widget());
806        frame(&mut element, &mut tree, 0.0, &log);
807
808        frame(&mut element, &mut tree, 123_456.0, &log);
809        let landed = (drawn_markers(&log), drawn_at(&log));
810
811        // Measuring the rows in view must not move the rows above them.
812        for _ in 0..5 {
813            frame(&mut element, &mut tree, 123_456.0, &log);
814            assert_eq!((drawn_markers(&log), drawn_at(&log)), landed);
815        }
816    }
817
818    #[test]
819    fn rows_added_at_the_front_leave_the_others_measured_and_in_their_state() {
820        let older = items(50, &[40.0, 100.0, 60.0]);
821        let (heights, log) = (RowHeights::default(), Log::default());
822        let mut element = list(&older, &heights, 0, &log);
823        let mut tree = Tree::new(element.as_widget());
824        frame(&mut element, &mut tree, 0.0, &log);
825        assert_eq!(drawn_markers(&log), [0, 1, 2, 3, 4]);
826
827        // A newer note arrives: key 900, 70px, in front of the rest. The app
828        // builds a new widget for the new list.
829        let mut newer = vec![(900, 70.0)];
830        newer.extend(older.iter().copied());
831        let mut rebuilt = list(&newer, &heights, 1_000, &log);
832        tree.diff(rebuilt.as_widget_mut());
833        frame(&mut rebuilt, &mut tree, 0.0, &log);
834
835        // The new row is new (marker 1900); rows 0..=3 are the same rows as
836        // before (their state kept its old marker), each 70px further down.
837        assert_eq!(drawn_markers(&log), [1_900, 0, 1, 2, 3]);
838        assert_eq!(drawn_at(&log), [0.0, 70.0, 110.0, 210.0, 270.0]);
839        assert_eq!(heights.get(&4), Some(100.0), "a row that left the view is still measured");
840    }
841
842    #[test]
843    fn measurements_outlive_the_widget_tree() {
844        let items = items(500, &[40.0, 100.0, 60.0, 30.0, 200.0]);
845        let (heights, log) = (RowHeights::default(), Log::default());
846        let mut element = list(&items, &heights, 0, &log);
847        let mut tree = Tree::new(element.as_widget());
848        let mut scroll = 0.0;
849        while scroll <= 2_000.0 {
850            frame(&mut element, &mut tree, scroll, &log);
851            scroll += 150.0;
852        }
853        let height = frame(&mut element, &mut tree, 1_800.0, &log);
854        let (rows, at) = (drawn_markers(&log), drawn_at(&log));
855
856        // The popup closes and opens again: a new widget and a new tree, the
857        // same heights. The list is the same height before anything is drawn,
858        // and scrolled back to 1800 it shows the same rows in the same places.
859        let mut reopened = list(&items, &heights, 0, &log);
860        let mut fresh = Tree::new(reopened.as_widget());
861        assert_eq!(lay_out(&mut reopened, &mut fresh, WIDTH).size().height, height);
862        frame(&mut reopened, &mut fresh, 1_800.0, &log);
863        assert_eq!((drawn_markers(&log), drawn_at(&log)), (rows, at));
864    }
865
866    /// A list of `items` that publishes `()` within 200px of its end.
867    fn telling_list<'a>(items: &'a [Item], heights: &'a RowHeights<u32>) -> Headless<'a> {
868        VirtualList::new(
869            items,
870            heights,
871            |item: &Item| item.0,
872            |_, _| ESTIMATE,
873            |_, (_, height)| Headless::new(Probe { height: *height, marker: 0, draws: Rc::default() }),
874        )
875        .on_near_end(200.0, ())
876        .into()
877    }
878
879    /// Lay the list out and hand it `event` scrolled to `scroll_y`. Returns
880    /// how many messages it published.
881    fn published(element: &mut Headless<'_>, tree: &mut Tree, scroll_y: f32, event: Event) -> usize {
882        let node = lay_out(element, tree, WIDTH);
883        let viewport = Rectangle::new(Point::new(0.0, scroll_y), Size::new(WIDTH, VIEW));
884        let mut messages = Vec::new();
885        element.as_widget_mut().update(
886            tree,
887            &event,
888            Layout::new(&node),
889            mouse::Cursor::Unavailable,
890            &(),
891            &mut clipboard::Null,
892            &mut Shell::new(&mut messages),
893            &viewport,
894        );
895        messages.len()
896    }
897
898    #[test]
899    fn nearing_the_end_is_told_once_for_each_place_and_never_while_redrawing() {
900        // Twenty 50px rows: the list ends at 1000, so with a 300px viewport
901        // "within 200px of the end" starts at a scroll of 500.
902        let items = items(20, &[50.0]);
903        let heights = RowHeights::default();
904        let mut element = telling_list(&items, &heights);
905        let mut tree = Tree::new(element.as_widget());
906        let moved = || Event::Mouse(mouse::Event::CursorMoved { position: Point::ORIGIN });
907        let redraw = || Event::Window(window::Event::RedrawRequested(std::time::Instant::now()));
908
909        assert_eq!(published(&mut element, &mut tree, 0.0, moved()), 0, "far from the end");
910        assert_eq!(published(&mut element, &mut tree, 499.0, moved()), 0, "201px from the end");
911        assert_eq!(published(&mut element, &mut tree, 500.0, redraw()), 0, "never while redrawing");
912        assert_eq!(published(&mut element, &mut tree, 500.0, moved()), 1, "200px from the end");
913        assert_eq!(published(&mut element, &mut tree, 500.0, moved()), 0, "said already, and nothing moved");
914        assert_eq!(published(&mut element, &mut tree, 560.0, moved()), 1, "scrolled on: ask again");
915
916        // The next page arrives: the end is far again, then near again.
917        let longer = self::items(40, &[50.0]);
918        let mut rebuilt = telling_list(&longer, &heights);
919        tree.diff(rebuilt.as_widget_mut());
920        assert_eq!(published(&mut rebuilt, &mut tree, 560.0, moved()), 0);
921        assert_eq!(published(&mut rebuilt, &mut tree, 1_500.0, moved()), 1);
922    }
923
924    #[test]
925    fn rows_are_as_tall_together_as_measured_or_else_estimated() {
926        // Rows of 80px, estimated at ESTIMATE until seen.
927        let items = items(20, &[80.0]);
928        let heights = RowHeights::default();
929        let total = |upto: usize| heights.total(&items[..upto], |item: &Item| item.0, |_, _| ESTIMATE);
930        assert_eq!(total(10), 10.0 * ESTIMATE);
931        // Each row starts where those before it end.
932        let starts = || heights.starts(&items, |item: &Item| item.0, |_, _| ESTIMATE);
933        assert_eq!(starts()[..3], [0.0, ESTIMATE, 2.0 * ESTIMATE]);
934        assert_eq!(starts().len(), items.len());
935
936        // A frame at the top measures the rows in view, the first four.
937        let mut element = list(&items, &heights, 0, &Log::default());
938        let mut tree = Tree::new(element.as_widget());
939        frame(&mut element, &mut tree, 0.0, &Log::default());
940        assert_eq!(total(4), 320.0);
941        assert_eq!(starts()[..6], [0.0, 80.0, 160.0, 240.0, 320.0, 320.0 + ESTIMATE]);
942        assert_eq!(total(10), 320.0 + 6.0 * ESTIMATE);
943    }
944
945    #[test]
946    fn another_width_measures_again() {
947        let items = items(100, &[40.0, 100.0]);
948        let (heights, log) = (RowHeights::default(), Log::default());
949        let mut element = list(&items, &heights, 0, &log);
950        let mut tree = Tree::new(element.as_widget());
951        frame(&mut element, &mut tree, 0.0, &log);
952        assert!(!heights.is_empty());
953
954        // Text wraps differently in a narrower list: old heights are wrong.
955        lay_out(&mut element, &mut tree, WIDTH - 50.0);
956        assert!(heights.is_empty());
957    }
958
959    #[test]
960    fn an_empty_list_has_no_height_and_builds_nothing() {
961        let items: Vec<Item> = Vec::new();
962        let (heights, log) = (RowHeights::default(), Log::default());
963        let mut element = list(&items, &heights, 0, &log);
964        let mut tree = Tree::new(element.as_widget());
965
966        assert_eq!(frame(&mut element, &mut tree, 0.0, &log), 0.0);
967        assert!(log.built.borrow().is_empty());
968        assert!(log.draws.borrow().is_empty());
969    }
970}