use alloc::vec::Vec;
use core::ops::Range;
use blit::{
Animation, AnimationOptions, Axis, Constraints, Id, Key, Layout, LayoutCx, Point, Rect, Scalar, Scope, Size, Ui,
internal::animator::Animator, state,
};
use super::{Scrollbar, ScrollbarInput, THUMB, TRACK, ThumbProgress, content_input, content_motion, scrollbar_input};
use crate::Context;
blit::builder! {
pub struct ScrollList<'a, T: Scalar> {
new(state: &'a mut ScrollListState<T>),
axis: Axis = Axis::Vertical,
#[into]
count: Option<usize> = None,
#[into]
animation: Animation = Animation::default(),
scroll_speed: f32 = 1.0,
inertia_friction: f32 = 2.5,
minimum_thumb_extent: T = T::from_f32(1.0),
floating: bool = false,
}
}
impl<'state, T: Scalar> ScrollList<'state, T> {
pub fn begin<'ui, C, S>(self, mut ui: Ui<'ui, C, S>) -> Rows<'state, 'ui, C>
where
C: Context<Scalar = T>,
S: state::NoLayout,
{
let Self {
state,
axis,
count,
animation,
scroll_speed,
inertia_friction,
minimum_thumb_extent,
floating,
} = self;
let viewport = ui.area();
let size = viewport.map_or(ui.screen().size(), |area| area.size());
let extent = axis.extent(size);
let overscan = extent.repeat(VIEWPORTS);
let motion = content_input(&mut ui, axis);
let (parts, rows) = (ui.scope(), ui.scope());
let (thumb_active, scrollbar) = scrollbar_input(&mut state.inertia, &mut ui, parts, axis, extent);
if motion.active || motion.deactivated || motion.delta != Point::ZERO || scrollbar.is_some() {
state.request = Request::default();
}
let movement = match scrollbar {
None => content_motion(
&mut state.inertia,
&mut ui,
axis,
scroll_speed,
inertia_friction,
motion,
),
Some(_) => 0.0,
};
if viewport.is_none() {
ui.request_frame();
}
let row = state.sample.get(state.visible.start).copied();
let current = state.first as f64
+ row.map_or(0.0, |row| {
(state.within.to_f32() / row.extent.to_f32()).clamp(0.0, 1.0) as f64
});
let (request_delta, request_seek) = advance_request(state, &mut ui, animation, count, overscan, current);
let row = state.sample.get(state.visible.start).copied();
let mut extra_delta = request_delta;
if state.sample.is_empty() && state.within.to_f32().abs() > overscan.to_f32() {
extra_delta = state.within.endpoint(extra_delta);
state.within = T::ZERO;
}
let delta = {
let delta: T = state.inertia.pixel_delta(movement);
let delta = delta.endpoint(extra_delta);
if delta.to_f32().abs() > overscan.to_f32() && state.average == 0.0 {
state.request.target = Goal::Delta(delta.to_f32());
state.request.applied = 0.0;
state.request.animator = None;
ui.request_frame();
T::ZERO
} else {
delta
}
};
let seek = match scrollbar {
None | Some(ScrollbarInput::Idle | ScrollbarInput::Thumb(0.0)) => request_seek.or_else(|| {
if delta.to_f32().abs() > overscan.to_f32()
&& state.average > 0.0
&& !row.zip(state.sample.last()).is_some_and(|(row, last)| {
let offset = row.top.endpoint(state.within).endpoint(delta);
offset >= T::ZERO && offset <= last.top.endpoint(last.extent)
})
{
Some((current + delta.to_f32() as f64 / state.average as f64).max(0.0))
} else {
None
}
}),
Some(ScrollbarInput::Thumb(value) | ScrollbarInput::Track(value)) => {
state.inertia.remainder = 0.0;
let offset = row.map_or(T::ZERO, |row| row.top.endpoint(state.within));
let (position, visible) = metrics(state, count, extent, offset);
let total = count.map_or(state.scrollbar.explored, |count| count as f64);
let maximum = (total - visible).max(0.0);
let previous = if count.is_some() {
position
} else {
state.scrollbar.position
};
let position = if matches!(scrollbar, Some(ScrollbarInput::Track(_))) {
value as f64 * maximum
} else {
(previous + value as f64 * maximum).clamp(0.0, maximum)
};
Some(match count {
Some(count) if position == maximum => count as f64,
Some(_) => position,
None if position == 0.0 => 0.0,
None => (current + position - previous).max(0.0),
})
}
};
let direction = seek.map_or(delta.to_f32() as f64, |position| position - current);
if let Some(position) = seek {
state.first = position as usize;
state.within = T::ZERO;
}
state.first = state.first.min(count.unwrap_or(usize::MAX).saturating_sub(1));
let anchor = Anchor {
index: state.first,
within: state.within,
delta,
fraction: seek.map(|position| (position - state.first as f64).clamp(0.0, 1.0) as f32),
};
let cross = axis.other();
let gutter = match floating {
true => T::ZERO,
false => {
let track = ui.resolve(parts, TRACK);
ui.node(track).area().map_or(T::ZERO, |area| cross.extent(area.size()))
}
};
let mut bounds = Constraints {
min: Size::ZERO,
max: Size::uniform(T::UNBOUNDED),
};
let width = (cross.extent(size) - gutter).max(T::ZERO);
cross.set_extent(&mut bounds.min, width);
cross.set_extent(&mut bounds.max, width);
let content = ui.clip(T::ZERO).layout(VirtualLayout {
axis,
anchor,
count,
size,
row_bounds: bounds,
scrollbar: Scrollbar {
minimum: minimum_thumb_extent,
floating,
},
});
state.sample.clear();
let list = List {
state,
content,
parts,
rows,
axis,
count,
anchor,
size,
bounds,
viewport,
movement,
direction,
thumb_active,
window: Window {
first: anchor.index,
end: anchor.index,
within: anchor.within,
..Window::default()
},
pending: None,
phase: Phase::Down,
progress: None,
};
Rows {
list,
keys: |index| index,
}
}
}
pub struct Rows<'state, 'ui, C: Context, K = fn(usize) -> usize> {
list: List<'state, 'ui, C>,
keys: K,
}
impl<'state, 'ui, C: Context, K> Rows<'state, 'ui, C, K> {
#[allow(clippy::should_implement_trait)]
pub fn next<O: Key>(&mut self) -> Option<(usize, Ui<'_, C>)>
where
K: FnMut(usize) -> O,
{
self.list.next(&mut self.keys)
}
pub fn keys<F, O>(self, keys: F) -> Rows<'state, 'ui, C, F>
where
F: FnMut(usize) -> O,
O: Key,
{
Rows { list: self.list, keys }
}
pub fn scrollbar(mut self, track: impl FnOnce(Ui<'_, C>), thumb: impl FnOnce(Ui<'_, C>, bool)) {
self.list.finish();
if let Some(progress) = self.list.progress.filter(|progress| progress.visible_fraction < 1.0) {
self.list
.content
.child_in(self.list.parts, TRACK)
.item(ListItem(Kind::Track(progress)))
.build(track);
let thumb_active = self.list.thumb_active;
self.list
.content
.child_in(self.list.parts, THUMB)
.item(ListItem(Kind::Thumb))
.build(|ui: Ui<'_, C>| thumb(ui, thumb_active));
}
}
}
struct List<'state, 'ui, C: Context> {
state: &'state mut ScrollListState<C::Scalar>,
content: Ui<'ui, C, state::Open<VirtualLayout<C::Scalar>>>,
parts: Scope,
rows: Scope,
axis: Axis,
count: Option<usize>,
anchor: Anchor<C::Scalar>,
size: Size<C::Scalar>,
bounds: Constraints<C::Scalar>,
viewport: Option<Rect<C::Scalar>>,
movement: f32,
direction: f64,
thumb_active: bool,
window: Window<C::Scalar>,
pending: Option<(usize, Id)>,
phase: Phase,
progress: Option<ThumbProgress>,
}
impl<C: Context> List<'_, '_, C> {
fn next<K: Key>(&mut self, key: impl FnOnce(usize) -> K) -> Option<(usize, Ui<'_, C>)> {
if self.phase == Phase::Done {
return None;
}
self.measure();
let window = &self.window;
let limit = self.count.unwrap_or(usize::MAX);
let extent = self.axis.extent(self.size);
let overscan = extent.repeat(VIEWPORTS);
let index = if self.phase == Phase::Down
&& window.end < limit
&& (window.end == self.anchor.index || window.after_anchor < window.within.endpoint(overscan).max(extent))
{
window.end
} else if window.first > 0
&& (-window.before_anchor > window.within
|| (window.end == limit && window.after_anchor.endpoint(window.before_anchor) < overscan))
{
self.phase = Phase::Up;
window.first - 1
} else {
self.finish();
return None;
};
let row = self
.content
.child_in(self.rows, key(index))
.item(ListItem(Kind::Row(index)));
self.pending = Some((index, row.id()));
Some((index, row))
}
fn measure(&mut self) {
let Some((index, node)) = self.pending.take() else {
return;
};
let extent = self.axis.extent(self.content.layout_child(node, self.bounds));
assert!(
extent.is_finite() && extent > C::Scalar::ZERO,
"virtual list rows need a positive extent"
);
let top = self.window.push(self.anchor, index, extent);
self.state.sample.push(Row { top, extent });
}
fn finish(&mut self) {
if self.phase == Phase::Done {
return;
}
self.measure();
self.phase = Phase::Done;
let state = &mut *self.state;
let window = &self.window;
let anchor = self.anchor;
let count = self.count;
let extent = self.axis.extent(self.size);
let first = window.first;
if first < anchor.index {
state.sample.reverse();
state.sample[anchor.index - first..].reverse();
for row in &mut state.sample {
row.top = row.top.endpoint(window.before_anchor);
}
}
let content_extent = window.after_anchor.endpoint(window.before_anchor);
let offset = window.offset(extent, count);
if (first == 0 && offset == C::Scalar::ZERO && self.movement < 0.0)
|| (count == Some(window.end)
&& offset == (content_extent - extent).max(C::Scalar::ZERO)
&& self.movement > 0.0)
{
state.inertia.velocity = 0.0;
state.inertia.remainder = 0.0;
}
state.visible = state
.sample
.partition_point(|row| row.top.endpoint(row.extent) <= offset)
..state.sample.partition_point(|row| row.top < offset.endpoint(extent));
if let Some(row) = state.sample.get(state.visible.start) {
state.first = first + state.visible.start;
state.within = offset - row.top;
} else {
state.first = first;
state.within = C::Scalar::ZERO;
}
if !state.sample.is_empty() {
state.average = content_extent.to_f32() / state.sample.len() as f32;
if state.scrollbar.scale == 0.0 {
state.scrollbar.scale = state.average;
}
}
let (position, visible) = metrics(state, count, extent, offset);
let progress = {
let scrollbar = &mut state.scrollbar;
if position == 0.0 {
scrollbar.position = 0.0;
} else if self.direction > 0.0 || scrollbar.position == 0.0 {
scrollbar.position = scrollbar.position.max(position);
} else if self.direction < 0.0 {
scrollbar.position = scrollbar.position.min(position);
}
let position = if count.is_some() { position } else { scrollbar.position };
scrollbar.explored = scrollbar.explored.max(position + visible * VIEWPORTS as f64);
let total = count.map_or(scrollbar.explored, |count| count as f64);
let scrollable = total - visible;
ThumbProgress {
position: if scrollable > 0.0 {
(position / scrollable) as f32
} else {
0.0
},
visible_fraction: if total > 0.0 {
(visible / total).clamp(0.0, 1.0) as f32
} else {
1.0
},
}
};
self.progress = Some(progress);
if self.viewport.is_none() {
state.first = anchor.index;
state.within = anchor.within.endpoint(anchor.delta);
state.sample.clear();
state.visible = 0..0;
}
}
}
impl<C: Context> Drop for List<'_, '_, C> {
fn drop(&mut self) {
self.finish();
}
}
#[derive(Default)]
pub struct ScrollListState<T> {
inertia: super::Inertia,
request: Request<T>,
first: usize,
within: T,
sample: Vec<Row<T>>,
visible: Range<usize>,
average: f32,
scrollbar: ScrollbarState,
}
#[derive(Default)]
struct Request<T> {
target: Goal<T>,
animator: Option<Animator<f32, 1>>,
applied: f32,
remainder: f32,
}
#[derive(Clone, Copy, Default)]
enum Goal<T> {
#[default]
None,
Delta(f32),
Row {
index: usize,
offset: T,
},
}
impl<T: Scalar> ScrollListState<T> {
pub fn scroll_by(&mut self, amount: T) {
self.inertia.stop();
let target = match self.request.target {
Goal::Delta(_) => self.request.applied + amount.to_f32(),
_ => {
self.request = Request::default();
amount.to_f32()
}
};
self.request.target = Goal::Delta(target);
}
pub fn scroll_to(&mut self, index: usize, offset: T) {
self.inertia.stop();
self.request = Request {
target: Goal::Row { index, offset },
..Request::default()
};
}
pub fn jump_to(&mut self, index: usize, offset: T) {
self.first = index;
self.scrollbar.position = index as f64;
self.within = offset;
self.sample.clear();
self.visible = 0..0;
self.stop();
}
pub fn stop(&mut self) {
self.inertia.stop();
self.request = Request::default();
}
pub fn is_moving(&self) -> bool {
!matches!(self.request.target, Goal::None) || self.inertia.velocity != 0.0
}
pub fn position(&self) -> (usize, T) {
(self.first, self.within)
}
}
fn advance_request<C: Context, S: state::Local>(
state: &mut ScrollListState<C::Scalar>,
ui: &mut Ui<'_, C, S>,
animation: Animation,
count: Option<usize>,
overscan: C::Scalar,
current: f64,
) -> (C::Scalar, Option<f64>) {
let instant = match animation {
Animation::Tween(tween) => tween.duration <= 0.0,
Animation::Spring(spring) => spring.duration <= 0.0,
};
if let Goal::Row { index, offset } = state.request.target {
let index = index.min(count.unwrap_or(usize::MAX).saturating_sub(1));
if instant {
state.jump_to(index, offset);
return (C::Scalar::ZERO, None);
}
if state.sample.is_empty() {
ui.request_frame();
return (C::Scalar::ZERO, None);
}
if state.request.animator.is_none()
&& let Some(first_row) = state.sample.get(state.visible.start)
&& let Some(window_first) = state.first.checked_sub(state.visible.start)
&& let Some(target_row) = index.checked_sub(window_first).and_then(|i| state.sample.get(i))
{
let current_top = first_row.top.endpoint(state.within);
let target_top = target_row.top.endpoint(offset);
state.request.target = Goal::Delta(target_top.to_f32() - current_top.to_f32());
}
}
match state.request.target {
Goal::None => (C::Scalar::ZERO, None),
Goal::Delta(target) => {
if (target - state.request.applied).abs() > overscan.to_f32() && state.average == 0.0 {
ui.request_frame();
return (C::Scalar::ZERO, None);
}
let request = &mut state.request;
let animator = request
.animator
.get_or_insert_with(|| Animator::new([request.applied], Animation::default()));
let (value, _) = animator.advance(
[target],
[true],
animation,
AnimationOptions::default(),
ui.time(),
true,
);
let step = value[0] - request.applied + request.remainder;
request.applied = value[0];
let whole = if step == 0.0 {
C::Scalar::ZERO
} else {
C::Scalar::from_f32(step)
};
request.remainder = step - whole.to_f32();
if animator.is_active() {
ui.request_frame();
} else {
*request = Request::default();
}
(whole, None)
}
Goal::Row { index, offset } => {
let index = index.min(count.unwrap_or(usize::MAX).saturating_sub(1));
let target = index as f64
+ if state.average > 0.0 {
offset.to_f32() as f64 / state.average as f64
} else {
0.0
};
let request = &mut state.request;
let animator = request
.animator
.get_or_insert_with(|| Animator::new([(current - target) as f32], Animation::default()));
animator.advance([0.0], [true], animation, AnimationOptions::default(), ui.time(), true);
let min = -(target as f32);
let max = count.map_or(f32::INFINITY, |count| (count.saturating_sub(1) as f64 - target) as f32);
let remaining = animator.clamp(0, min, max, ui.time());
if animator.is_active() {
ui.request_frame();
(C::Scalar::ZERO, Some((target + remaining as f64).max(0.0)))
} else {
state.jump_to(index, offset);
(C::Scalar::ZERO, None)
}
}
}
}
#[derive(Clone, Copy)]
struct ListItem(Kind);
impl Default for ListItem {
fn default() -> Self {
Self(Kind::Row(0))
}
}
#[derive(Clone, Copy)]
enum Kind {
Row(usize),
Track(ThumbProgress),
Thumb,
}
const VIEWPORTS: usize = 2;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Phase {
Down,
Up,
Done,
}
#[derive(Clone, Copy)]
struct Row<T> {
top: T,
extent: T,
}
#[derive(Clone, Copy)]
struct Anchor<T> {
index: usize,
within: T,
delta: T,
fraction: Option<f32>,
}
#[derive(Default)]
struct Window<T> {
first: usize,
end: usize,
after_anchor: T,
before_anchor: T,
within: T,
}
impl<T: Scalar> Window<T> {
fn push(&mut self, anchor: Anchor<T>, index: usize, extent: T) -> T {
self.first = self.first.min(index);
self.end = self.end.max(index + 1);
if index == anchor.index {
self.within = match anchor.fraction {
Some(fraction) => T::from_f32(extent.to_f32() * fraction),
None => anchor.within.min(extent).endpoint(anchor.delta),
};
}
if index < anchor.index {
self.before_anchor = self.before_anchor.endpoint(extent);
-self.before_anchor
} else {
let top = self.after_anchor;
self.after_anchor = self.after_anchor.endpoint(extent);
top
}
}
fn offset(&self, viewport: T, count: Option<usize>) -> T {
let offset = self.within.endpoint(self.before_anchor);
let offset = if self.first == 0 { offset.max(T::ZERO) } else { offset };
if count == Some(self.end) {
offset.min((self.after_anchor.endpoint(self.before_anchor) - viewport).max(T::ZERO))
} else {
offset
}
}
}
#[derive(Clone, Copy, Default)]
struct ScrollbarState {
scale: f32,
position: f64,
explored: f64,
}
struct VirtualLayout<T> {
axis: Axis,
anchor: Anchor<T>,
count: Option<usize>,
size: Size<T>,
row_bounds: Constraints<T>,
scrollbar: Scrollbar<T>,
}
impl<C: Context<Scalar = T>, T: Scalar> Layout<C> for VirtualLayout<T> {
type Item = ListItem;
fn fit(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis) -> blit::Fit<T> {
if axis == self.axis {
let mut window = Window {
first: self.anchor.index,
end: self.anchor.index,
..Window::default()
};
for child in cx.children() {
if let Kind::Row(index) = cx.item(child).0 {
let extent = cx.fit(child, axis).natural;
window.push(self.anchor, index, extent);
}
}
let content_extent = window.after_anchor.endpoint(window.before_anchor);
let natural = content_extent.endpoint(if self.count == Some(window.end) {
T::ZERO
} else {
axis.extent(self.size)
});
blit::Fit::new(T::ZERO, natural)
} else {
let cross = axis.extent(self.size);
if cross > T::ZERO {
blit::Fit::exact(cross)
} else {
let mut max = blit::Fit::ZERO;
for child in cx.children() {
if let Kind::Row(_) = cx.item(child).0 {
max = max.max(cx.fit(child, axis));
}
}
max
}
}
}
fn distribute(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis, extent: T) {
let mut track = None;
let mut thumb = None;
if axis == self.axis {
let mut window = Window {
first: self.anchor.index,
end: self.anchor.index,
..Window::default()
};
for child in cx.children() {
match cx.item(child).0 {
Kind::Row(index) => {
let row_extent = cx.set_extent(child, cx.fit(child, axis).natural);
window.push(self.anchor, index, row_extent);
}
Kind::Track(progress) => track = Some((child, progress)),
Kind::Thumb => thumb = Some(child),
}
}
let content_extent = window.after_anchor.endpoint(window.before_anchor);
let offset = window.offset(extent, self.count);
let mut positions = Window::default();
for child in cx.children() {
if let Kind::Row(index) = cx.item(child).0 {
let row_extent = axis.extent(cx.size(child));
let top = positions
.push(self.anchor, index, row_extent)
.endpoint(window.before_anchor)
- offset;
cx.set_offset(child, top);
}
}
if offset < T::ZERO || content_extent - offset < extent && self.count != Some(window.end) {
cx.request_frame();
}
if let Some(((track, progress), thumb)) = track.zip(thumb) {
self.scrollbar.distribute_main(cx, extent, progress, track, thumb);
}
} else {
for child in cx.children() {
match cx.item(child).0 {
Kind::Row(_) => {
let assigned = axis
.extent(self.row_bounds.max)
.min(extent)
.max(axis.extent(self.row_bounds.min));
cx.set_extent(child, assigned);
cx.set_offset(child, T::ZERO);
}
Kind::Track(progress) => track = Some((child, progress)),
Kind::Thumb => thumb = Some(child),
}
}
if let Some(((track, _), thumb)) = track.zip(thumb) {
let thickness = cx.fit(track, axis).natural.min(extent);
self.scrollbar.distribute_cross(cx, extent, thickness, track, thumb);
}
}
if axis == Axis::Vertical && cx.size(cx.node()) != self.size {
cx.request_frame();
}
}
}
fn metrics<T: Scalar>(state: &ScrollListState<T>, count: Option<usize>, extent: T, offset: T) -> (f64, f64) {
let position_at = |index, offset: T| {
state.sample.get(index).map_or(state.first as f64, |row: &Row<T>| {
state.first as f64 + index as f64 - state.visible.start as f64
+ ((offset - row.top).to_f32() / row.extent.to_f32()).clamp(0.0, 1.0) as f64
})
};
let position = position_at(state.visible.start, offset);
let visible = if count.is_some() {
position_at(state.visible.end.saturating_sub(1), offset.endpoint(extent)) - position
} else {
let scale = if state.scrollbar.scale > 0.0 {
state.scrollbar.scale
} else {
state.average
};
extent.to_f32() as f64 / scale as f64
};
(position, visible)
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use blit::{
FrameInfo, Scope, Tree,
input::{Input, TouchPhase},
};
use super::*;
use crate::test::{TestContext, pointer};
#[test]
fn shrinking_anchor_keeps_the_window_bounded() {
for count in [Some(1_000_000), None] {
let mut tree = Tree::default();
let mut state = ScrollListState::default();
let tall = |index| (index as u64, 10_000.0);
settle_frame(&mut tree, &mut state, count, tall);
state.scroll_by(5_000.0);
settle_frame(&mut tree, &mut state, count, tall);
settle_frame(&mut tree, &mut state, count, |index| (index as u64, 1.0));
assert!(state.sample.len() <= 101);
assert_eq!(state.position().0, 1);
assert_eq!(
tree.find(Scope::ROOT, 1usize).and_then(|id| tree.area(id)).unwrap().y,
0.0
);
}
}
#[test]
fn queued_movement_and_position_preserve_the_row_offset() {
for count in [Some(1_000_000), None] {
let mut tree = Tree::default();
let mut state = ScrollListState::default();
state.scroll_by(5_000_000.0);
settle_frame(&mut tree, &mut state, count, |index| (index as u64, 10.0));
assert_eq!(state.position().0, 500_000);
state.scroll_by(1.0);
state.scroll_by(5.0);
render_frame(&mut tree, &mut state, count, Input::None, |index| (index as u64, 10.0));
let (index, offset) = state.position();
assert_eq!(offset, 5.0);
state.scroll_to(index + 1, offset);
let (area, _) = render_frame(
&mut tree,
&mut state,
count.map(|count| count + 1),
Input::None,
|index| {
let id = if index == 0 {
u32::MAX as u64
} else {
(index - 1) as u64
};
(id, 10.0)
},
);
assert_eq!(state.position(), (500_001, 5.0));
assert_eq!(area.unwrap().y, -5.0);
}
}
#[test]
fn thumb_end_seeks_the_finite_or_explored_boundary() {
for id in [None, Some(1)] {
for (count, extents) in [
(Some(1), &[1_000.0][..]),
(Some(3), &[10.0, 10.0, 1_000.0]),
(Some(20), &[10.0; 20]),
(Some(3), &[10.0, 500.0, 10.0]),
(Some(2), &[10.0, 10.0]),
(None, &[10.0]),
] {
let mut tree = Tree::default();
let mut state = ScrollListState::default();
let row = |index: usize| (index as u64, extents[index % extents.len()]);
settle_frame(&mut tree, &mut state, count, row);
for phase in [TouchPhase::Down, TouchPhase::Up] {
render_frame(&mut tree, &mut state, count, pointer(id, phase, 79.5, 49.999), row);
}
if tree.has_pending_redraw() {
settle_frame(&mut tree, &mut state, count, row);
}
if let Some(count) = count {
let area = tree.find(Scope::ROOT, count - 1).and_then(|id| tree.area(id)).unwrap();
assert_eq!(area.y + area.height, extents.iter().sum::<f32>().min(50.0));
} else {
assert_eq!(state.position().0, 5);
assert_eq!(state.within, 0.0);
}
}
}
}
#[test]
fn variable_rows_keep_the_thumb_moving_with_the_scroll() {
let mut tree = Tree::default();
let mut state = ScrollListState::default();
let row = |index| (index as u64, [1.0, 1024.0, 16.0, 512.0][index % 4]);
let mut previous = settle_frame(&mut tree, &mut state, None, row).1.unwrap();
for delta in [16.0, -16.0] {
for _ in 0..400 {
state.scroll_by(delta);
let thumb = render_frame(&mut tree, &mut state, None, Input::None, row).1.unwrap();
assert!((thumb.y - previous.y) * delta >= -0.0001);
if delta > 0.0 {
assert!(thumb.height <= previous.height);
}
assert!(thumb.y >= 0.0 && thumb.y + thumb.height <= 50.00001);
let idle = render_frame(&mut tree, &mut state, None, Input::None, row).1.unwrap();
assert_eq!(idle, thumb);
assert!(!tree.has_pending_redraw());
previous = thumb;
}
}
assert_eq!(previous.y, 0.0);
}
#[test]
fn scrolling_up_preserves_the_existing_row_position() {
for count in [Some(1_000), None] {
for (before, after) in [(1024.0, 16.0), (16.0, 1024.0)] {
let mut tree = Tree::default();
let mut state = ScrollListState::default();
let row = |index| (index as u64, if index < 20 { before } else { after });
state.scroll_to(20, 0.0);
settle_frame(&mut tree, &mut state, count, row);
let key = 20usize as u64;
let id = tree.find(Scope::ROOT, key).unwrap();
let y = tree.area(id).unwrap().y;
state.scroll_by(-20.0);
render_frame(&mut tree, &mut state, count, Input::None, row);
assert_eq!(tree.area(id).unwrap().y, y + 20.0);
settle_frame(&mut tree, &mut state, count, row);
assert_eq!(tree.area(id).unwrap().y, y + 20.0);
state.scroll_by(40.0);
render_frame(&mut tree, &mut state, count, Input::None, row);
assert_eq!(tree.area(id).unwrap().y, y - 20.0);
}
}
}
#[test]
fn horizontal_rows_flow_along_x() {
let mut tree = Tree::default();
let mut state = ScrollListState::default();
for _ in 0..2 {
tree.build(
&mut TestContext,
FrameInfo::new(Size::new(50.0, 20.0)),
Duration::ZERO,
Input::None,
|ui: Ui<'_, TestContext>| {
let mut list = ScrollList::new(&mut state).axis(Axis::Horizontal).count(10).begin(ui);
while let Some((index, row)) = list.next() {
row.constrain(Constraints::tight(Size::new(10.0, 20.0)))
.layout(())
.child_in(Scope::ROOT, index)
.insert(());
}
},
);
tree.layout(&mut TestContext);
}
assert_eq!(
tree.find(Scope::ROOT, 2usize).and_then(|id| tree.area(id)),
Some(Rect::new(20.0, 0.0, 10.0, 20.0))
);
}
#[test]
fn animated_requests_settle_nearby_and_far() {
let mut tree = Tree::default();
let mut state = ScrollListState::default();
let animation = blit::Tween::new(0.250, blit::Easing::LINEAR);
let mut step = |state: &mut ScrollListState<f32>, millis| {
tree.build(
&mut TestContext,
FrameInfo::new(Size::new(80.0, 50.0)),
Duration::from_millis(millis),
Input::None,
|ui: Ui<'_, TestContext>| {
let mut list = ScrollList::new(state).count(1_000).animation(animation).begin(ui);
while let Some((_, row)) = list.next() {
row.constrain(Constraints::tight(Size::new(80.0, 10.0))).insert(());
}
},
);
tree.layout(&mut TestContext);
};
step(&mut state, 0);
step(&mut state, 0);
state.scroll_by(100.0);
step(&mut state, 0);
step(&mut state, 125);
assert_eq!(state.position(), (5, 0.0));
assert!(state.is_moving());
step(&mut state, 250);
assert_eq!(state.position(), (10, 0.0));
assert!(!state.is_moving());
state.scroll_to(12, 4.0);
step(&mut state, 250);
step(&mut state, 375);
assert_eq!(state.position(), (11, 2.0));
step(&mut state, 500);
assert_eq!(state.position(), (12, 4.0));
assert!(!state.is_moving());
state.scroll_to(500, 3.0);
step(&mut state, 500);
step(&mut state, 625);
assert!(state.position().0 > 100 && state.position().0 < 500);
assert!(state.is_moving());
step(&mut state, 750);
assert_eq!(state.position(), (500, 3.0));
assert!(!state.is_moving());
state.jump_to(0, 0.0);
step(&mut state, 750);
assert_eq!(state.position(), (0, 0.0));
assert!(!state.is_moving());
}
fn settle_frame(
tree: &mut Tree<TestContext>,
state: &mut ScrollListState<f32>,
count: Option<usize>,
row: impl Fn(usize) -> (u64, f32),
) -> (Option<Rect<f32>>, Option<Rect<f32>>) {
for _ in 0..8 {
let result = render_frame(tree, state, count, Input::None, &row);
if !tree.has_pending_redraw() {
return result;
}
}
panic!("virtual list did not converge");
}
fn render_frame(
tree: &mut Tree<TestContext>,
state: &mut ScrollListState<f32>,
count: Option<usize>,
input: Input<f32>,
row: impl Fn(usize) -> (u64, f32),
) -> (Option<Rect<f32>>, Option<Rect<f32>>) {
let mut thumb = None;
tree.build(
&mut TestContext,
FrameInfo::new(Size::new(80.0, 50.0)),
Duration::ZERO,
input,
|ui: Ui<'_, TestContext>| {
let track = |ui: Ui<'_, TestContext>| {
ui.constrain(Constraints {
min: Size::uniform(1.0),
max: Size::uniform(f32::INFINITY),
});
};
let mut list = ScrollList::new(&mut *state)
.count(count)
.begin(ui)
.keys(|index| row(index).0);
while let Some((index, ui)) = list.next() {
let (id, extent) = row(index);
ui.constrain(Constraints::tight(Size::new(79.0, extent)))
.layout(())
.child_in(Scope::ROOT, id)
.insert(());
}
list.scrollbar(track, |ui, _| thumb = Some(ui.id()));
},
);
tree.layout(&mut TestContext);
(
tree.find(Scope::ROOT, row(state.position().0).0)
.and_then(|id| tree.area(id)),
thumb.and_then(|id| tree.area(id)),
)
}
}