Skip to main content

blit_widget/scroll/
list.rs

1use alloc::vec::Vec;
2use core::ops::Range;
3
4use blit::{
5    Animation, AnimationOptions, Axis, Constraints, Id, Key, Layout, LayoutCx, Point, Rect, Scalar, Scope, Size, Ui,
6    internal::animator::Animator, state,
7};
8
9use super::{Scrollbar, ScrollbarInput, THUMB, TRACK, ThumbProgress, content_input, content_motion, scrollbar_input};
10use crate::Context;
11
12blit::builder! {
13    /// use for large lists with variable or unknown row extents
14    /// measures a bounded viewport window and estimates remaining extents
15    /// rows must have positive finite extents along the axis
16    /// an absent count scrolls indefinitely with a thumb covering the explored range
17    pub struct ScrollList<'a, T: Scalar> {
18        new(state: &'a mut ScrollListState<T>),
19        axis: Axis = Axis::Vertical,
20        #[into]
21        count: Option<usize> = None,
22        #[into]
23        animation: Animation = Animation::default(),
24        scroll_speed: f32 = 1.0,
25        inertia_friction: f32 = 2.5,
26        minimum_thumb_extent: T = T::from_f32(1.0),
27        /// scrollbars cover the content instead of taking space beside it
28        floating: bool = false,
29    }
30}
31
32impl<'state, T: Scalar> ScrollList<'state, T> {
33    /// starts the list in `ui`, whose rows then come from [`Rows::next`]
34    pub fn begin<'ui, C, S>(self, mut ui: Ui<'ui, C, S>) -> Rows<'state, 'ui, C>
35    where
36        C: Context<Scalar = T>,
37        S: state::NoLayout,
38    {
39        let Self {
40            state,
41            axis,
42            count,
43            animation,
44            scroll_speed,
45            inertia_friction,
46            minimum_thumb_extent,
47            floating,
48        } = self;
49        let viewport = ui.area();
50        let size = viewport.map_or(ui.screen().size(), |area| area.size());
51        let extent = axis.extent(size);
52        let overscan = extent.repeat(VIEWPORTS);
53        let motion = content_input(&mut ui, axis);
54        // the scrollbar and the rows key into scopes of their own, so no row key meets a part
55        let (parts, rows) = (ui.scope(), ui.scope());
56        let (thumb_active, scrollbar) = scrollbar_input(&mut state.inertia, &mut ui, parts, axis, extent);
57        if motion.active || motion.deactivated || motion.delta != Point::ZERO || scrollbar.is_some() {
58            state.request = Request::default();
59        }
60        let movement = match scrollbar {
61            None => content_motion(
62                &mut state.inertia,
63                &mut ui,
64                axis,
65                scroll_speed,
66                inertia_friction,
67                motion,
68            ),
69            Some(_) => 0.0,
70        };
71        if viewport.is_none() {
72            ui.request_frame();
73        }
74        let row = state.sample.get(state.visible.start).copied();
75        let current = state.first as f64
76            + row.map_or(0.0, |row| {
77                (state.within.to_f32() / row.extent.to_f32()).clamp(0.0, 1.0) as f64
78            });
79        let (request_delta, request_seek) = advance_request(state, &mut ui, animation, count, overscan, current);
80        let row = state.sample.get(state.visible.start).copied();
81        // treat large offsets into an unmeasured window as movement so the existing seek logic estimates the row
82        let mut extra_delta = request_delta;
83        if state.sample.is_empty() && state.within.to_f32().abs() > overscan.to_f32() {
84            extra_delta = state.within.endpoint(extra_delta);
85            state.within = T::ZERO;
86        }
87        let delta = {
88            let delta: T = state.inertia.pixel_delta(movement);
89            let delta = delta.endpoint(extra_delta);
90            if delta.to_f32().abs() > overscan.to_f32() && state.average == 0.0 {
91                // wait for the initial extents before estimating a large jump
92                state.request.target = Goal::Delta(delta.to_f32());
93                state.request.applied = 0.0;
94                state.request.animator = None;
95                ui.request_frame();
96                T::ZERO
97            } else {
98                delta
99            }
100        };
101        let seek = match scrollbar {
102            None | Some(ScrollbarInput::Idle | ScrollbarInput::Thumb(0.0)) => request_seek.or_else(|| {
103                if delta.to_f32().abs() > overscan.to_f32()
104                    && state.average > 0.0
105                    && !row.zip(state.sample.last()).is_some_and(|(row, last)| {
106                        let offset = row.top.endpoint(state.within).endpoint(delta);
107                        offset >= T::ZERO && offset <= last.top.endpoint(last.extent)
108                    })
109                {
110                    Some((current + delta.to_f32() as f64 / state.average as f64).max(0.0))
111                } else {
112                    None
113                }
114            }),
115            Some(ScrollbarInput::Thumb(value) | ScrollbarInput::Track(value)) => {
116                state.inertia.remainder = 0.0;
117                let offset = row.map_or(T::ZERO, |row| row.top.endpoint(state.within));
118                let (position, visible) = metrics(state, count, extent, offset);
119                let total = count.map_or(state.scrollbar.explored, |count| count as f64);
120                let maximum = (total - visible).max(0.0);
121                let previous = if count.is_some() {
122                    position
123                } else {
124                    state.scrollbar.position
125                };
126                let position = if matches!(scrollbar, Some(ScrollbarInput::Track(_))) {
127                    value as f64 * maximum
128                } else {
129                    (previous + value as f64 * maximum).clamp(0.0, maximum)
130                };
131                Some(match count {
132                    Some(count) if position == maximum => count as f64,
133                    Some(_) => position,
134                    None if position == 0.0 => 0.0,
135                    None => (current + position - previous).max(0.0),
136                })
137            }
138        };
139        let direction = seek.map_or(delta.to_f32() as f64, |position| position - current);
140        if let Some(position) = seek {
141            state.first = position as usize;
142            state.within = T::ZERO;
143        }
144        state.first = state.first.min(count.unwrap_or(usize::MAX).saturating_sub(1));
145        let anchor = Anchor {
146            index: state.first,
147            within: state.within,
148            delta,
149            fraction: seek.map(|position| (position - state.first as f64).clamp(0.0, 1.0) as f32),
150        };
151        // the track sized the gutter last frame
152        let cross = axis.other();
153        let gutter = match floating {
154            true => T::ZERO,
155            false => {
156                let track = ui.resolve(parts, TRACK);
157                ui.node(track).area().map_or(T::ZERO, |area| cross.extent(area.size()))
158            }
159        };
160        let mut bounds = Constraints {
161            min: Size::ZERO,
162            max: Size::uniform(T::UNBOUNDED),
163        };
164        let width = (cross.extent(size) - gutter).max(T::ZERO);
165        cross.set_extent(&mut bounds.min, width);
166        cross.set_extent(&mut bounds.max, width);
167        let content = ui.clip(T::ZERO).layout(VirtualLayout {
168            axis,
169            anchor,
170            count,
171            size,
172            row_bounds: bounds,
173            scrollbar: Scrollbar {
174                minimum: minimum_thumb_extent,
175                floating,
176            },
177        });
178        state.sample.clear();
179        let list = List {
180            state,
181            content,
182            parts,
183            rows,
184            axis,
185            count,
186            anchor,
187            size,
188            bounds,
189            viewport,
190            movement,
191            direction,
192            thumb_active,
193            window: Window {
194                first: anchor.index,
195                end: anchor.index,
196                within: anchor.within,
197                ..Window::default()
198            },
199            pending: None,
200            phase: Phase::Down,
201            progress: None,
202        };
203        Rows {
204            list,
205            keys: |index| index,
206        }
207    }
208}
209
210/// the rows of a [`ScrollList`], measured as they are built
211///
212/// rows are keyed by their index unless [`Rows::keys`] names them.
213/// finish with [`Rows::scrollbar`] to draw a scrollbar
214pub struct Rows<'state, 'ui, C: Context, K = fn(usize) -> usize> {
215    list: List<'state, 'ui, C>,
216    keys: K,
217}
218
219impl<'state, 'ui, C: Context, K> Rows<'state, 'ui, C, K> {
220    /// the next row to build and its index, until the viewport is covered
221    #[allow(clippy::should_implement_trait)]
222    pub fn next<O: Key>(&mut self) -> Option<(usize, Ui<'_, C>)>
223    where
224        K: FnMut(usize) -> O,
225    {
226        self.list.next(&mut self.keys)
227    }
228
229    /// names the row at each index, so a row keeps its state as rows before it come and go
230    pub fn keys<F, O>(self, keys: F) -> Rows<'state, 'ui, C, F>
231    where
232        F: FnMut(usize) -> O,
233        O: Key,
234    {
235        Rows { list: self.list, keys }
236    }
237
238    /// builds the scrollbar once the rows are done
239    pub fn scrollbar(mut self, track: impl FnOnce(Ui<'_, C>), thumb: impl FnOnce(Ui<'_, C>, bool)) {
240        self.list.finish();
241        if let Some(progress) = self.list.progress.filter(|progress| progress.visible_fraction < 1.0) {
242            self.list
243                .content
244                .child_in(self.list.parts, TRACK)
245                .item(ListItem(Kind::Track(progress)))
246                .build(track);
247            let thumb_active = self.list.thumb_active;
248            self.list
249                .content
250                .child_in(self.list.parts, THUMB)
251                .item(ListItem(Kind::Thumb))
252                .build(|ui: Ui<'_, C>| thumb(ui, thumb_active));
253        }
254    }
255}
256
257// everything but the keys, which finishes state updates when dropped and so cannot be taken apart
258struct List<'state, 'ui, C: Context> {
259    state: &'state mut ScrollListState<C::Scalar>,
260    content: Ui<'ui, C, state::Open<VirtualLayout<C::Scalar>>>,
261    parts: Scope,
262    rows: Scope,
263    axis: Axis,
264    count: Option<usize>,
265    anchor: Anchor<C::Scalar>,
266    size: Size<C::Scalar>,
267    bounds: Constraints<C::Scalar>,
268    viewport: Option<Rect<C::Scalar>>,
269    movement: f32,
270    direction: f64,
271    thumb_active: bool,
272    window: Window<C::Scalar>,
273    // the row handed out last, measured on the next call
274    pending: Option<(usize, Id)>,
275    phase: Phase,
276    progress: Option<ThumbProgress>,
277}
278
279impl<C: Context> List<'_, '_, C> {
280    fn next<K: Key>(&mut self, key: impl FnOnce(usize) -> K) -> Option<(usize, Ui<'_, C>)> {
281        if self.phase == Phase::Done {
282            return None;
283        }
284        self.measure();
285        let window = &self.window;
286        let limit = self.count.unwrap_or(usize::MAX);
287        let extent = self.axis.extent(self.size);
288        let overscan = extent.repeat(VIEWPORTS);
289        let index = if self.phase == Phase::Down
290            && window.end < limit
291            && (window.end == self.anchor.index || window.after_anchor < window.within.endpoint(overscan).max(extent))
292        {
293            window.end
294        } else if window.first > 0
295            && (-window.before_anchor > window.within
296                || (window.end == limit && window.after_anchor.endpoint(window.before_anchor) < overscan))
297        {
298            self.phase = Phase::Up;
299            window.first - 1
300        } else {
301            self.finish();
302            return None;
303        };
304        let row = self
305            .content
306            .child_in(self.rows, key(index))
307            .item(ListItem(Kind::Row(index)));
308        self.pending = Some((index, row.id()));
309        Some((index, row))
310    }
311
312    // the row built since the last call joins the window
313    fn measure(&mut self) {
314        let Some((index, node)) = self.pending.take() else {
315            return;
316        };
317        let extent = self.axis.extent(self.content.layout_child(node, self.bounds));
318        assert!(
319            extent.is_finite() && extent > C::Scalar::ZERO,
320            "virtual list rows need a positive extent"
321        );
322        let top = self.window.push(self.anchor, index, extent);
323        self.state.sample.push(Row { top, extent });
324    }
325
326    fn finish(&mut self) {
327        if self.phase == Phase::Done {
328            return;
329        }
330        self.measure();
331        self.phase = Phase::Done;
332        let state = &mut *self.state;
333        let window = &self.window;
334        let anchor = self.anchor;
335        let count = self.count;
336        let extent = self.axis.extent(self.size);
337        let first = window.first;
338        if first < anchor.index {
339            state.sample.reverse();
340            state.sample[anchor.index - first..].reverse();
341            for row in &mut state.sample {
342                row.top = row.top.endpoint(window.before_anchor);
343            }
344        }
345        let content_extent = window.after_anchor.endpoint(window.before_anchor);
346        let offset = window.offset(extent, count);
347        if (first == 0 && offset == C::Scalar::ZERO && self.movement < 0.0)
348            || (count == Some(window.end)
349                && offset == (content_extent - extent).max(C::Scalar::ZERO)
350                && self.movement > 0.0)
351        {
352            state.inertia.velocity = 0.0;
353            state.inertia.remainder = 0.0;
354        }
355        state.visible = state
356            .sample
357            .partition_point(|row| row.top.endpoint(row.extent) <= offset)
358            ..state.sample.partition_point(|row| row.top < offset.endpoint(extent));
359        if let Some(row) = state.sample.get(state.visible.start) {
360            state.first = first + state.visible.start;
361            state.within = offset - row.top;
362        } else {
363            state.first = first;
364            state.within = C::Scalar::ZERO;
365        }
366        if !state.sample.is_empty() {
367            state.average = content_extent.to_f32() / state.sample.len() as f32;
368            if state.scrollbar.scale == 0.0 {
369                state.scrollbar.scale = state.average;
370            }
371        }
372        let (position, visible) = metrics(state, count, extent, offset);
373        let progress = {
374            let scrollbar = &mut state.scrollbar;
375            if position == 0.0 {
376                scrollbar.position = 0.0;
377            } else if self.direction > 0.0 || scrollbar.position == 0.0 {
378                scrollbar.position = scrollbar.position.max(position);
379            } else if self.direction < 0.0 {
380                scrollbar.position = scrollbar.position.min(position);
381            }
382            // publish measurement corrections only while scrolling in that direction
383            let position = if count.is_some() { position } else { scrollbar.position };
384            scrollbar.explored = scrollbar.explored.max(position + visible * VIEWPORTS as f64);
385            let total = count.map_or(scrollbar.explored, |count| count as f64);
386            let scrollable = total - visible;
387            ThumbProgress {
388                position: if scrollable > 0.0 {
389                    (position / scrollable) as f32
390                } else {
391                    0.0
392                },
393                visible_fraction: if total > 0.0 {
394                    (visible / total).clamp(0.0, 1.0) as f32
395                } else {
396                    1.0
397                },
398            }
399        };
400        self.progress = Some(progress);
401        if self.viewport.is_none() {
402            // preserve the anchor until the viewport is known
403            state.first = anchor.index;
404            state.within = anchor.within.endpoint(anchor.delta);
405            state.sample.clear();
406            state.visible = 0..0;
407        }
408    }
409}
410
411impl<C: Context> Drop for List<'_, '_, C> {
412    fn drop(&mut self) {
413        self.finish();
414    }
415}
416
417#[derive(Default)]
418pub struct ScrollListState<T> {
419    inertia: super::Inertia,
420    request: Request<T>,
421
422    // retain the viewport position when the window is replaced
423    first: usize,
424    within: T,
425
426    // retain measurements only for the viewport window and estimate the rest
427    sample: Vec<Row<T>>,
428    visible: Range<usize>,
429    average: f32,
430
431    // fix the infinite scrollbar scale after the initial measurement
432    scrollbar: ScrollbarState,
433}
434
435#[derive(Default)]
436struct Request<T> {
437    target: Goal<T>,
438    animator: Option<Animator<f32, 1>>,
439    applied: f32,
440    remainder: f32,
441}
442
443#[derive(Clone, Copy, Default)]
444enum Goal<T> {
445    #[default]
446    None,
447    Delta(f32),
448    Row {
449        index: usize,
450        offset: T,
451    },
452}
453
454impl<T: Scalar> ScrollListState<T> {
455    /// replaces the movement in pixels queued for the next build
456    pub fn scroll_by(&mut self, amount: T) {
457        self.inertia.stop();
458        let target = match self.request.target {
459            Goal::Delta(_) => self.request.applied + amount.to_f32(),
460            _ => {
461                self.request = Request::default();
462                amount.to_f32()
463            }
464        };
465        self.request.target = Goal::Delta(target);
466    }
467
468    /// scrolls to a list index and pixel offset
469    /// - nearby offsets use exact row measurements
470    /// - large offscreen offsets use estimated row extents
471    pub fn scroll_to(&mut self, index: usize, offset: T) {
472        self.inertia.stop();
473        self.request = Request {
474            target: Goal::Row { index, offset },
475            ..Request::default()
476        };
477    }
478
479    /// jumps immediately to a list index and pixel offset without animation
480    pub fn jump_to(&mut self, index: usize, offset: T) {
481        self.first = index;
482        self.scrollbar.position = index as f64;
483        self.within = offset;
484        self.sample.clear();
485        self.visible = 0..0;
486        self.stop();
487    }
488
489    pub fn stop(&mut self) {
490        self.inertia.stop();
491        self.request = Request::default();
492    }
493
494    pub fn is_moving(&self) -> bool {
495        !matches!(self.request.target, Goal::None) || self.inertia.velocity != 0.0
496    }
497
498    /// returns the row index and pixel offset
499    pub fn position(&self) -> (usize, T) {
500        (self.first, self.within)
501    }
502}
503
504fn advance_request<C: Context, S: state::Local>(
505    state: &mut ScrollListState<C::Scalar>,
506    ui: &mut Ui<'_, C, S>,
507    animation: Animation,
508    count: Option<usize>,
509    overscan: C::Scalar,
510    current: f64,
511) -> (C::Scalar, Option<f64>) {
512    let instant = match animation {
513        Animation::Tween(tween) => tween.duration <= 0.0,
514        Animation::Spring(spring) => spring.duration <= 0.0,
515    };
516    if let Goal::Row { index, offset } = state.request.target {
517        let index = index.min(count.unwrap_or(usize::MAX).saturating_sub(1));
518        if instant {
519            state.jump_to(index, offset);
520            return (C::Scalar::ZERO, None);
521        }
522        if state.sample.is_empty() {
523            ui.request_frame();
524            return (C::Scalar::ZERO, None);
525        }
526        // nearby targets convert to exact pixel deltas before starting a row space seek
527        if state.request.animator.is_none()
528            && let Some(first_row) = state.sample.get(state.visible.start)
529            && let Some(window_first) = state.first.checked_sub(state.visible.start)
530            && let Some(target_row) = index.checked_sub(window_first).and_then(|i| state.sample.get(i))
531        {
532            let current_top = first_row.top.endpoint(state.within);
533            let target_top = target_row.top.endpoint(offset);
534            state.request.target = Goal::Delta(target_top.to_f32() - current_top.to_f32());
535        }
536    }
537    match state.request.target {
538        Goal::None => (C::Scalar::ZERO, None),
539        Goal::Delta(target) => {
540            if (target - state.request.applied).abs() > overscan.to_f32() && state.average == 0.0 {
541                ui.request_frame();
542                return (C::Scalar::ZERO, None);
543            }
544            let request = &mut state.request;
545            let animator = request
546                .animator
547                .get_or_insert_with(|| Animator::new([request.applied], Animation::default()));
548            let (value, _) = animator.advance(
549                [target],
550                [true],
551                animation,
552                AnimationOptions::default(),
553                ui.time(),
554                true,
555            );
556            let step = value[0] - request.applied + request.remainder;
557            request.applied = value[0];
558            let whole = if step == 0.0 {
559                C::Scalar::ZERO
560            } else {
561                C::Scalar::from_f32(step)
562            };
563            request.remainder = step - whole.to_f32();
564            if animator.is_active() {
565                ui.request_frame();
566            } else {
567                *request = Request::default();
568            }
569            (whole, None)
570        }
571        Goal::Row { index, offset } => {
572            let index = index.min(count.unwrap_or(usize::MAX).saturating_sub(1));
573            let target = index as f64
574                + if state.average > 0.0 {
575                    offset.to_f32() as f64 / state.average as f64
576                } else {
577                    0.0
578                };
579            let request = &mut state.request;
580            let animator = request
581                .animator
582                .get_or_insert_with(|| Animator::new([(current - target) as f32], Animation::default()));
583            animator.advance([0.0], [true], animation, AnimationOptions::default(), ui.time(), true);
584            let min = -(target as f32);
585            let max = count.map_or(f32::INFINITY, |count| (count.saturating_sub(1) as f64 - target) as f32);
586            let remaining = animator.clamp(0, min, max, ui.time());
587            if animator.is_active() {
588                ui.request_frame();
589                (C::Scalar::ZERO, Some((target + remaining as f64).max(0.0)))
590            } else {
591                state.jump_to(index, offset);
592                (C::Scalar::ZERO, None)
593            }
594        }
595    }
596}
597
598#[derive(Clone, Copy)]
599struct ListItem(Kind);
600
601impl Default for ListItem {
602    fn default() -> Self {
603        Self(Kind::Row(0))
604    }
605}
606
607#[derive(Clone, Copy)]
608enum Kind {
609    Row(usize),
610    Track(ThumbProgress),
611    Thumb,
612}
613
614const VIEWPORTS: usize = 2;
615
616// rows extend forward from the anchor, then backward above it
617#[derive(Clone, Copy, PartialEq, Eq)]
618enum Phase {
619    Down,
620    Up,
621    Done,
622}
623
624#[derive(Clone, Copy)]
625struct Row<T> {
626    top: T,
627    extent: T,
628}
629
630#[derive(Clone, Copy)]
631struct Anchor<T> {
632    index: usize,
633    within: T,
634    delta: T,
635    fraction: Option<f32>,
636}
637
638#[derive(Default)]
639struct Window<T> {
640    first: usize,
641    end: usize,
642    after_anchor: T,
643    before_anchor: T,
644    within: T,
645}
646
647impl<T: Scalar> Window<T> {
648    // rows arrive forward from the anchor then backward
649    fn push(&mut self, anchor: Anchor<T>, index: usize, extent: T) -> T {
650        self.first = self.first.min(index);
651        self.end = self.end.max(index + 1);
652        if index == anchor.index {
653            self.within = match anchor.fraction {
654                Some(fraction) => T::from_f32(extent.to_f32() * fraction),
655                None => anchor.within.min(extent).endpoint(anchor.delta),
656            };
657        }
658        if index < anchor.index {
659            self.before_anchor = self.before_anchor.endpoint(extent);
660            -self.before_anchor
661        } else {
662            let top = self.after_anchor;
663            self.after_anchor = self.after_anchor.endpoint(extent);
664            top
665        }
666    }
667
668    fn offset(&self, viewport: T, count: Option<usize>) -> T {
669        let offset = self.within.endpoint(self.before_anchor);
670        let offset = if self.first == 0 { offset.max(T::ZERO) } else { offset };
671        if count == Some(self.end) {
672            offset.min((self.after_anchor.endpoint(self.before_anchor) - viewport).max(T::ZERO))
673        } else {
674            offset
675        }
676    }
677}
678
679#[derive(Clone, Copy, Default)]
680struct ScrollbarState {
681    scale: f32,
682    position: f64,
683    explored: f64,
684}
685
686struct VirtualLayout<T> {
687    axis: Axis,
688    anchor: Anchor<T>,
689    count: Option<usize>,
690    size: Size<T>,
691    row_bounds: Constraints<T>,
692    scrollbar: Scrollbar<T>,
693}
694
695impl<C: Context<Scalar = T>, T: Scalar> Layout<C> for VirtualLayout<T> {
696    type Item = ListItem;
697
698    fn fit(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis) -> blit::Fit<T> {
699        if axis == self.axis {
700            let mut window = Window {
701                first: self.anchor.index,
702                end: self.anchor.index,
703                ..Window::default()
704            };
705            for child in cx.children() {
706                if let Kind::Row(index) = cx.item(child).0 {
707                    let extent = cx.fit(child, axis).natural;
708                    window.push(self.anchor, index, extent);
709                }
710            }
711            let content_extent = window.after_anchor.endpoint(window.before_anchor);
712            let natural = content_extent.endpoint(if self.count == Some(window.end) {
713                T::ZERO
714            } else {
715                axis.extent(self.size)
716            });
717            blit::Fit::new(T::ZERO, natural)
718        } else {
719            let cross = axis.extent(self.size);
720            if cross > T::ZERO {
721                blit::Fit::exact(cross)
722            } else {
723                let mut max = blit::Fit::ZERO;
724                for child in cx.children() {
725                    if let Kind::Row(_) = cx.item(child).0 {
726                        max = max.max(cx.fit(child, axis));
727                    }
728                }
729                max
730            }
731        }
732    }
733
734    fn distribute(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis, extent: T) {
735        let mut track = None;
736        let mut thumb = None;
737        if axis == self.axis {
738            let mut window = Window {
739                first: self.anchor.index,
740                end: self.anchor.index,
741                ..Window::default()
742            };
743            for child in cx.children() {
744                match cx.item(child).0 {
745                    Kind::Row(index) => {
746                        let row_extent = cx.set_extent(child, cx.fit(child, axis).natural);
747                        window.push(self.anchor, index, row_extent);
748                    }
749                    Kind::Track(progress) => track = Some((child, progress)),
750                    Kind::Thumb => thumb = Some(child),
751                }
752            }
753            let content_extent = window.after_anchor.endpoint(window.before_anchor);
754            let offset = window.offset(extent, self.count);
755            let mut positions = Window::default();
756            for child in cx.children() {
757                if let Kind::Row(index) = cx.item(child).0 {
758                    let row_extent = axis.extent(cx.size(child));
759                    let top = positions
760                        .push(self.anchor, index, row_extent)
761                        .endpoint(window.before_anchor)
762                        - offset;
763                    cx.set_offset(child, top);
764                }
765            }
766            if offset < T::ZERO || content_extent - offset < extent && self.count != Some(window.end) {
767                cx.request_frame();
768            }
769            if let Some(((track, progress), thumb)) = track.zip(thumb) {
770                self.scrollbar.distribute_main(cx, extent, progress, track, thumb);
771            }
772        } else {
773            for child in cx.children() {
774                match cx.item(child).0 {
775                    Kind::Row(_) => {
776                        let assigned = axis
777                            .extent(self.row_bounds.max)
778                            .min(extent)
779                            .max(axis.extent(self.row_bounds.min));
780                        cx.set_extent(child, assigned);
781                        cx.set_offset(child, T::ZERO);
782                    }
783                    Kind::Track(progress) => track = Some((child, progress)),
784                    Kind::Thumb => thumb = Some(child),
785                }
786            }
787            if let Some(((track, _), thumb)) = track.zip(thumb) {
788                let thickness = cx.fit(track, axis).natural.min(extent);
789                self.scrollbar.distribute_cross(cx, extent, thickness, track, thumb);
790            }
791        }
792        if axis == Axis::Vertical && cx.size(cx.node()) != self.size {
793            cx.request_frame();
794        }
795    }
796}
797
798fn metrics<T: Scalar>(state: &ScrollListState<T>, count: Option<usize>, extent: T, offset: T) -> (f64, f64) {
799    let position_at = |index, offset: T| {
800        state.sample.get(index).map_or(state.first as f64, |row: &Row<T>| {
801            state.first as f64 + index as f64 - state.visible.start as f64
802                + ((offset - row.top).to_f32() / row.extent.to_f32()).clamp(0.0, 1.0) as f64
803        })
804    };
805    let position = position_at(state.visible.start, offset);
806    let visible = if count.is_some() {
807        position_at(state.visible.end.saturating_sub(1), offset.endpoint(extent)) - position
808    } else {
809        let scale = if state.scrollbar.scale > 0.0 {
810            state.scrollbar.scale
811        } else {
812            state.average
813        };
814        extent.to_f32() as f64 / scale as f64
815    };
816    (position, visible)
817}
818
819#[cfg(test)]
820mod tests {
821    use std::time::Duration;
822
823    use blit::{
824        FrameInfo, Scope, Tree,
825        input::{Input, TouchPhase},
826    };
827
828    use super::*;
829    use crate::test::{TestContext, pointer};
830
831    #[test]
832    fn shrinking_anchor_keeps_the_window_bounded() {
833        for count in [Some(1_000_000), None] {
834            let mut tree = Tree::default();
835            let mut state = ScrollListState::default();
836            let tall = |index| (index as u64, 10_000.0);
837            settle_frame(&mut tree, &mut state, count, tall);
838            state.scroll_by(5_000.0);
839            settle_frame(&mut tree, &mut state, count, tall);
840            settle_frame(&mut tree, &mut state, count, |index| (index as u64, 1.0));
841            assert!(state.sample.len() <= 101);
842            assert_eq!(state.position().0, 1);
843            assert_eq!(
844                tree.find(Scope::ROOT, 1usize).and_then(|id| tree.area(id)).unwrap().y,
845                0.0
846            );
847        }
848    }
849
850    #[test]
851    fn queued_movement_and_position_preserve_the_row_offset() {
852        for count in [Some(1_000_000), None] {
853            let mut tree = Tree::default();
854            let mut state = ScrollListState::default();
855            state.scroll_by(5_000_000.0);
856            settle_frame(&mut tree, &mut state, count, |index| (index as u64, 10.0));
857            assert_eq!(state.position().0, 500_000);
858            state.scroll_by(1.0);
859            state.scroll_by(5.0);
860            render_frame(&mut tree, &mut state, count, Input::None, |index| (index as u64, 10.0));
861            let (index, offset) = state.position();
862            assert_eq!(offset, 5.0);
863            state.scroll_to(index + 1, offset);
864            let (area, _) = render_frame(
865                &mut tree,
866                &mut state,
867                count.map(|count| count + 1),
868                Input::None,
869                |index| {
870                    let id = if index == 0 {
871                        u32::MAX as u64
872                    } else {
873                        (index - 1) as u64
874                    };
875                    (id, 10.0)
876                },
877            );
878            assert_eq!(state.position(), (500_001, 5.0));
879            assert_eq!(area.unwrap().y, -5.0);
880        }
881    }
882
883    #[test]
884    fn thumb_end_seeks_the_finite_or_explored_boundary() {
885        for id in [None, Some(1)] {
886            for (count, extents) in [
887                (Some(1), &[1_000.0][..]),
888                (Some(3), &[10.0, 10.0, 1_000.0]),
889                (Some(20), &[10.0; 20]),
890                (Some(3), &[10.0, 500.0, 10.0]),
891                (Some(2), &[10.0, 10.0]),
892                (None, &[10.0]),
893            ] {
894                let mut tree = Tree::default();
895                let mut state = ScrollListState::default();
896                let row = |index: usize| (index as u64, extents[index % extents.len()]);
897                settle_frame(&mut tree, &mut state, count, row);
898                for phase in [TouchPhase::Down, TouchPhase::Up] {
899                    render_frame(&mut tree, &mut state, count, pointer(id, phase, 79.5, 49.999), row);
900                }
901                if tree.has_pending_redraw() {
902                    settle_frame(&mut tree, &mut state, count, row);
903                }
904                if let Some(count) = count {
905                    let area = tree.find(Scope::ROOT, count - 1).and_then(|id| tree.area(id)).unwrap();
906                    assert_eq!(area.y + area.height, extents.iter().sum::<f32>().min(50.0));
907                } else {
908                    assert_eq!(state.position().0, 5);
909                    assert_eq!(state.within, 0.0);
910                }
911            }
912        }
913    }
914
915    #[test]
916    fn variable_rows_keep_the_thumb_moving_with_the_scroll() {
917        let mut tree = Tree::default();
918        let mut state = ScrollListState::default();
919        let row = |index| (index as u64, [1.0, 1024.0, 16.0, 512.0][index % 4]);
920        let mut previous = settle_frame(&mut tree, &mut state, None, row).1.unwrap();
921        for delta in [16.0, -16.0] {
922            for _ in 0..400 {
923                state.scroll_by(delta);
924                let thumb = render_frame(&mut tree, &mut state, None, Input::None, row).1.unwrap();
925                assert!((thumb.y - previous.y) * delta >= -0.0001);
926                if delta > 0.0 {
927                    assert!(thumb.height <= previous.height);
928                }
929                assert!(thumb.y >= 0.0 && thumb.y + thumb.height <= 50.00001);
930                let idle = render_frame(&mut tree, &mut state, None, Input::None, row).1.unwrap();
931                assert_eq!(idle, thumb);
932                assert!(!tree.has_pending_redraw());
933                previous = thumb;
934            }
935        }
936        assert_eq!(previous.y, 0.0);
937    }
938
939    #[test]
940    fn scrolling_up_preserves_the_existing_row_position() {
941        for count in [Some(1_000), None] {
942            for (before, after) in [(1024.0, 16.0), (16.0, 1024.0)] {
943                let mut tree = Tree::default();
944                let mut state = ScrollListState::default();
945                let row = |index| (index as u64, if index < 20 { before } else { after });
946                state.scroll_to(20, 0.0);
947                settle_frame(&mut tree, &mut state, count, row);
948                let key = 20usize as u64;
949                let id = tree.find(Scope::ROOT, key).unwrap();
950                let y = tree.area(id).unwrap().y;
951                state.scroll_by(-20.0);
952                render_frame(&mut tree, &mut state, count, Input::None, row);
953                assert_eq!(tree.area(id).unwrap().y, y + 20.0);
954                settle_frame(&mut tree, &mut state, count, row);
955                assert_eq!(tree.area(id).unwrap().y, y + 20.0);
956                state.scroll_by(40.0);
957                render_frame(&mut tree, &mut state, count, Input::None, row);
958                assert_eq!(tree.area(id).unwrap().y, y - 20.0);
959            }
960        }
961    }
962
963    #[test]
964    fn horizontal_rows_flow_along_x() {
965        let mut tree = Tree::default();
966        let mut state = ScrollListState::default();
967        for _ in 0..2 {
968            tree.build(
969                &mut TestContext,
970                FrameInfo::new(Size::new(50.0, 20.0)),
971                Duration::ZERO,
972                Input::None,
973                |ui: Ui<'_, TestContext>| {
974                    let mut list = ScrollList::new(&mut state).axis(Axis::Horizontal).count(10).begin(ui);
975                    while let Some((index, row)) = list.next() {
976                        row.constrain(Constraints::tight(Size::new(10.0, 20.0)))
977                            .layout(())
978                            .child_in(Scope::ROOT, index)
979                            .insert(());
980                    }
981                },
982            );
983            tree.layout(&mut TestContext);
984        }
985        assert_eq!(
986            tree.find(Scope::ROOT, 2usize).and_then(|id| tree.area(id)),
987            Some(Rect::new(20.0, 0.0, 10.0, 20.0))
988        );
989    }
990
991    #[test]
992    fn animated_requests_settle_nearby_and_far() {
993        let mut tree = Tree::default();
994        let mut state = ScrollListState::default();
995        let animation = blit::Tween::new(0.250, blit::Easing::LINEAR);
996        let mut step = |state: &mut ScrollListState<f32>, millis| {
997            tree.build(
998                &mut TestContext,
999                FrameInfo::new(Size::new(80.0, 50.0)),
1000                Duration::from_millis(millis),
1001                Input::None,
1002                |ui: Ui<'_, TestContext>| {
1003                    let mut list = ScrollList::new(state).count(1_000).animation(animation).begin(ui);
1004                    while let Some((_, row)) = list.next() {
1005                        row.constrain(Constraints::tight(Size::new(80.0, 10.0))).insert(());
1006                    }
1007                },
1008            );
1009            tree.layout(&mut TestContext);
1010        };
1011        step(&mut state, 0);
1012        step(&mut state, 0);
1013
1014        // animated scroll_by
1015        state.scroll_by(100.0);
1016        step(&mut state, 0);
1017        step(&mut state, 125);
1018        assert_eq!(state.position(), (5, 0.0));
1019        assert!(state.is_moving());
1020        step(&mut state, 250);
1021        assert_eq!(state.position(), (10, 0.0));
1022        assert!(!state.is_moving());
1023
1024        // nearby animated scroll_to (inside sample window)
1025        state.scroll_to(12, 4.0);
1026        step(&mut state, 250);
1027        step(&mut state, 375);
1028        assert_eq!(state.position(), (11, 2.0));
1029        step(&mut state, 500);
1030        assert_eq!(state.position(), (12, 4.0));
1031        assert!(!state.is_moving());
1032
1033        // far animated scroll_to (outside sample window)
1034        state.scroll_to(500, 3.0);
1035        step(&mut state, 500);
1036        step(&mut state, 625);
1037        assert!(state.position().0 > 100 && state.position().0 < 500);
1038        assert!(state.is_moving());
1039        step(&mut state, 750);
1040        assert_eq!(state.position(), (500, 3.0));
1041        assert!(!state.is_moving());
1042
1043        // jump_to skips animation
1044        state.jump_to(0, 0.0);
1045        step(&mut state, 750);
1046        assert_eq!(state.position(), (0, 0.0));
1047        assert!(!state.is_moving());
1048    }
1049
1050    fn settle_frame(
1051        tree: &mut Tree<TestContext>,
1052        state: &mut ScrollListState<f32>,
1053        count: Option<usize>,
1054        row: impl Fn(usize) -> (u64, f32),
1055    ) -> (Option<Rect<f32>>, Option<Rect<f32>>) {
1056        for _ in 0..8 {
1057            let result = render_frame(tree, state, count, Input::None, &row);
1058            if !tree.has_pending_redraw() {
1059                return result;
1060            }
1061        }
1062        panic!("virtual list did not converge");
1063    }
1064
1065    fn render_frame(
1066        tree: &mut Tree<TestContext>,
1067        state: &mut ScrollListState<f32>,
1068        count: Option<usize>,
1069        input: Input<f32>,
1070        row: impl Fn(usize) -> (u64, f32),
1071    ) -> (Option<Rect<f32>>, Option<Rect<f32>>) {
1072        let mut thumb = None;
1073        tree.build(
1074            &mut TestContext,
1075            FrameInfo::new(Size::new(80.0, 50.0)),
1076            Duration::ZERO,
1077            input,
1078            |ui: Ui<'_, TestContext>| {
1079                // a track at least one unit thick on the right edge
1080                let track = |ui: Ui<'_, TestContext>| {
1081                    ui.constrain(Constraints {
1082                        min: Size::uniform(1.0),
1083                        max: Size::uniform(f32::INFINITY),
1084                    });
1085                };
1086                let mut list = ScrollList::new(&mut *state)
1087                    .count(count)
1088                    .begin(ui)
1089                    .keys(|index| row(index).0);
1090                while let Some((index, ui)) = list.next() {
1091                    let (id, extent) = row(index);
1092                    // a marker in the root scope covers the row so the tree can find it
1093                    ui.constrain(Constraints::tight(Size::new(79.0, extent)))
1094                        .layout(())
1095                        .child_in(Scope::ROOT, id)
1096                        .insert(());
1097                }
1098                list.scrollbar(track, |ui, _| thumb = Some(ui.id()));
1099            },
1100        );
1101        tree.layout(&mut TestContext);
1102        (
1103            tree.find(Scope::ROOT, row(state.position().0).0)
1104                .and_then(|id| tree.area(id)),
1105            thumb.and_then(|id| tree.area(id)),
1106        )
1107    }
1108}