use rustc_hash::FxHashMap;
use crate::{
fenwick::Fenwick,
ops::{CellSlot, ListAlignment, ListContentStyle, Viewability},
};
const OVERSCAN: f32 = 1.0;
const URGENT_STEPS: f32 = 4.0;
const LEAD_DECAY: f32 = 0.75;
const END_THRESHOLD: f32 = 1.0;
const START_THRESHOLD: f32 = 1.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(super) struct Edges {
pub(super) end: bool,
pub(super) start: bool,
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Slot {
pub(super) cell: u32,
pub(super) index: Option<u32>,
pub(super) rendered: Option<u32>,
pub(super) requested: Option<u32>,
}
impl Slot {
pub(super) fn ready(&self) -> Option<u32> {
match (self.index, self.rendered) {
(Some(i), Some(r)) if i == r && self.cell != u32::MAX => Some(i),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Extra {
pub(super) cell: u32,
pub(super) size: f32,
}
impl Extra {
const NONE: Self = Self {
cell: u32::MAX,
size: 0.0,
};
fn present(&self) -> bool {
self.cell != u32::MAX
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ExtraKind {
Header = 0,
Footer = 1,
Empty = 2,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Blocks {
pub(super) header: f32,
pub(super) body: f32,
pub(super) footer: f32,
pub(super) total: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum PendingScroll {
By(f32),
To(f32),
}
pub(super) fn replay(offset: f32, pending: &[(u32, PendingScroll)]) -> f32 {
let mut at = offset;
for &(_, scroll) in pending {
match scroll {
PendingScroll::By(d) => at += d,
PendingScroll::To(t) => at = t,
}
}
at
}
fn next_lead(lead: f32, step: f32, viewport: f32) -> f32 {
let kept = lead.abs() * LEAD_DECAY;
if step.signum() == lead.signum() && lead.abs() <= viewport && kept > step.abs() {
lead.signum() * kept
} else {
step
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Outer {
pub(super) view: u32,
pub(super) scrolls: bool,
pub(super) depth: u32,
}
#[derive(Debug)]
struct SetAside {
inverted: bool,
follow_end: Option<f32>,
alignment: ListAlignment,
}
pub(super) mod ignored {
pub(crate) const INVERTED: u16 = 1 << 0;
pub(crate) const FOLLOW_END: u16 = 1 << 1;
pub(crate) const ALIGNMENT: u16 = 1 << 2;
pub(crate) const ON_SCROLL: u16 = 1 << 3;
pub(crate) const SCROLL_VALUE: u16 = 1 << 4;
pub(crate) const REFRESH: u16 = 1 << 5;
pub(crate) const BEHAVIOR: u16 = 1 << 6;
pub(crate) const SCROLLBAR: u16 = 1 << 7;
pub(crate) const VIEWPORT: u16 = 1 << 8;
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum PinTarget {
End,
Index {
index: u32,
view_position: f32,
view_offset: f32,
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Pin {
target: PinTarget,
at: f32,
animating: bool,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Follow {
Stay,
By(f32),
To(f32),
}
const PIN_SLACK: f32 = 1.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct StickyRange {
pub(super) cell: u32,
pub(super) start: f32,
pub(super) end: f32,
pub(super) offset: Option<crate::animation::NodeId>,
}
#[derive(Debug)]
pub(super) struct ListState {
pub(super) count: u32,
estimated: f32,
pub(super) columns: u32,
sizes: Vec<f32>,
rows: Fenwick,
pub(super) slots: Vec<Slot>,
by_index: FxHashMap<u32, u32>,
free: Vec<u32>,
pub(super) extras: [Extra; 3],
pub(super) content: ListContentStyle,
content_style: ListContentStyle,
content_class: ListContentStyle,
pub(super) horizontal: bool,
mirrored: bool,
pub(super) inverted: bool,
pub(super) follow_end: Option<f32>,
pub(super) alignment: ListAlignment,
pub(super) sticky: Vec<u32>,
kept: Vec<u32>,
sticky_offset: f32,
sticky_node: Option<crate::animation::NodeId>,
pub(super) sent_sticky: Vec<StickyRange>,
pub(super) viewability: Viewability,
pub(super) viewable: Option<(u32, u32)>,
pub(super) end_threshold: f32,
pub(super) start_threshold: f32,
pub(super) offset: f32,
pub(super) viewport: f32,
pub(super) dirty: bool,
pub(super) cells_cross: f32,
load_more_at: Option<u32>,
load_more_at_start: Option<u32>,
pub(super) loads_at_start: bool,
moved_by_scroll: bool,
anchored_end: f32,
measured_scroll: f32,
issued: u32,
pending: Vec<(u32, PendingScroll)>,
moved: Vec<(u32, u32)>,
pub(super) items_changed: bool,
pub(super) paced: bool,
lead: f32,
splice_anchor: f32,
pin: Option<Pin>,
columns_anchor: Option<u32>,
pub(super) parent: bool,
pub(super) outer: Option<Outer>,
outer_start: f32,
limits: (f32, f32),
pub(super) spacer: Option<(taffy::NodeId, f32)>,
set_aside: Option<Box<SetAside>>,
pub(super) ignored: u16,
pub(super) warned: u16,
}
impl ListState {
pub(super) fn new() -> Self {
Self {
count: 0,
estimated: 50.0,
columns: 1,
sizes: Vec::new(),
rows: Fenwick::default(),
slots: Vec::new(),
by_index: FxHashMap::default(),
free: Vec::new(),
extras: [Extra::NONE; 3],
mirrored: false,
content: ListContentStyle::default(),
content_style: ListContentStyle::default(),
content_class: ListContentStyle::default(),
horizontal: false,
inverted: false,
follow_end: None,
alignment: ListAlignment::Top,
sticky: Vec::new(),
kept: Vec::new(),
sticky_offset: 0.0,
sticky_node: None,
sent_sticky: Vec::new(),
viewability: Viewability::default(),
viewable: None,
end_threshold: END_THRESHOLD,
start_threshold: START_THRESHOLD,
offset: 0.0,
viewport: 0.0,
dirty: true,
cells_cross: f32::NAN,
load_more_at: None,
load_more_at_start: None,
loads_at_start: false,
moved_by_scroll: false,
anchored_end: f32::NAN,
measured_scroll: 0.0,
issued: 0,
pending: Vec::new(),
moved: Vec::new(),
items_changed: false,
paced: false,
lead: 0.0,
splice_anchor: 0.0,
pin: None,
columns_anchor: None,
parent: false,
outer: None,
outer_start: f32::NAN,
limits: (0.0, 0.0),
spacer: None,
set_aside: None,
ignored: 0,
warned: 0,
}
}
pub(super) fn set_parent(&mut self, parent: bool) {
if parent == self.parent {
return;
}
self.parent = parent;
self.outer = None;
self.outer_start = f32::NAN;
self.pin = None;
self.dirty = true;
self.anchored_end = f32::NAN;
if parent {
let set_aside = SetAside {
inverted: std::mem::take(&mut self.inverted),
follow_end: self.follow_end.take(),
alignment: std::mem::take(&mut self.alignment),
};
if set_aside.inverted {
self.ignored |= ignored::INVERTED;
}
if set_aside.follow_end.is_some() {
self.ignored |= ignored::FOLLOW_END;
}
if set_aside.alignment != ListAlignment::Top {
self.ignored |= ignored::ALIGNMENT;
}
self.set_aside = Some(Box::new(set_aside));
} else if let Some(set_aside) = self.set_aside.take() {
let SetAside {
inverted,
follow_end,
alignment,
} = *set_aside;
self.inverted = inverted;
self.follow_end = follow_end;
self.alignment = alignment;
}
}
pub(super) fn set_outer(
&mut self,
start: f32,
offset: f32,
viewport: f32,
max: f32,
settled: bool,
) -> bool {
let shift = start - self.outer_start;
if shift != 0.0
&& !shift.is_nan()
&& let Some(pin) = &mut self.pin
{
pin.at -= shift;
}
self.outer_start = start;
self.limits = (-start, (max - start).max(-start));
let resized = viewport != self.viewport;
self.viewport = viewport;
let before = self.offset;
self.moved_to(offset - start, settled);
resized || before != self.offset
}
pub(super) fn clamped(&self, offset: f32) -> f32 {
let (min, max) = self.offset_limits();
offset.clamp(min, max)
}
fn offset_limits(&self) -> (f32, f32) {
if self.parent {
self.limits
} else {
(0.0, (self.content_len() - self.viewport).max(0.0))
}
}
pub(super) fn splice(&mut self, at: u32, removed: u32, inserted: u32) {
let at = at.min(self.count);
let removed = removed.min(self.count - at);
if removed == 0 && inserted == 0 {
return;
}
self.items_changed = true;
self.pin = None;
let anchor = self.visible_anchor();
let natural_before = self.natural_offset();
let end = (at + removed) as usize;
self.sizes.splice(
at as usize..end,
std::iter::repeat_n(f32::NAN, inserted as usize),
);
self.count = self.count - removed + inserted;
let shift = |i: u32| -> Option<u32> {
if i < at {
Some(i)
} else if i >= at + removed {
Some(i - removed + inserted)
} else {
None
}
};
self.kept = self.kept.iter().filter_map(|&i| shift(i)).collect();
self.by_index.clear();
for (slot, s) in self.slots.iter_mut().enumerate() {
let index = s.index.and_then(shift);
let Some(new) = index else {
if s.index.take().is_some() {
self.free.push(slot as u32);
} else if let (Some(r), Some(n)) = (s.requested, s.requested.and_then(shift))
&& s.rendered == Some(r)
{
s.requested = Some(n);
s.rendered = Some(n);
if n != r {
self.moved.push((slot as u32, n));
}
continue;
}
s.rendered = None;
s.requested = None;
continue;
};
s.index = Some(new);
s.rendered = s.rendered.and_then(shift);
match s.requested.map(|r| (r, shift(r))) {
Some((r, Some(n))) => {
s.requested = Some(n);
if n != r {
self.moved.push((slot as u32, n));
}
}
Some((_, None)) => {
s.requested = None;
s.rendered = None;
}
None => {}
}
self.by_index.insert(new, slot as u32);
}
self.free.sort_unstable();
self.free.dedup();
if removed == 0 && at + inserted == self.count {
self.resize_rows(at);
} else {
self.rebuild_offsets();
}
if self.load_more_at.is_some() {
self.load_more_at = None;
}
if let Some((index, from_top)) = anchor
&& index >= at + removed
{
let moved_to = index - removed + inserted;
if self.inverted {
let delta = (self.item_at(moved_to) - from_top).max(0.0) - natural_before;
self.offset -= delta;
self.splice_anchor -= delta;
} else {
self.keep_in_place(moved_to, from_top);
}
}
}
fn visible_anchor(&self) -> Option<(u32, f32)> {
(self.count > 0
&& self.viewport > 0.0
&& self.keeps_visible_rows()
&& (self.offset > 0.0 || (!self.parent && self.loads_at_start)))
.then(|| {
let top = self.natural_offset();
let body = self.blocks().body;
let row = self.rows.find((top - body).max(0.0) as f64) as u32;
let index = (row * self.columns).min(self.count - 1);
(index, self.item_at(index) - top)
})
}
pub(super) fn scroll_position(&self) -> Option<(u32, f32)> {
if self.count == 0 || self.viewport <= 0.0 {
return None;
}
let top = self.natural_offset();
let body = self.blocks().body;
let row = (self.rows.find((top - body).max(0.0) as f64) as u32).min(self.row_count() - 1);
let index = (row * self.columns).min(self.count - 1);
Some((index, top - self.item_at(index)))
}
fn keep_in_place(&mut self, index: u32, from_top: f32) {
let delta = self.item_at(index) - from_top - self.natural_offset();
self.offset += delta;
self.splice_anchor += delta;
}
fn keeps_visible_rows(&self) -> bool {
self.keeps_visible_rows_at(self.natural_offset())
}
fn keeps_visible_rows_at(&self, natural: f32) -> bool {
!self.inverted
|| (self.loads_at_start && !self.anchored_end.is_nan() && natural > PIN_SLACK)
}
fn measuring_natural_offset(&self) -> f32 {
if self.inverted && !self.anchored_end.is_nan() {
self.anchored_end - self.offset - self.measured_scroll
} else {
self.natural_offset()
}
}
pub(super) fn take_splice_anchor(&mut self) -> f32 {
std::mem::take(&mut self.splice_anchor)
}
pub(super) fn issue_scroll_by(&mut self, delta: f32) {
self.issued += 1;
self.pending.push((self.issued, PendingScroll::By(delta)));
}
pub(super) fn issue_scroll_to(&mut self, offset: f32) {
self.issued += 1;
self.pending.push((self.issued, PendingScroll::To(offset)));
}
pub(super) fn reported(&mut self, offset: f32, applied: u32) {
self.pending.retain(|&(n, _)| n > applied);
let at = replay(offset, &self.pending);
self.moved_to(at, self.pending.is_empty());
}
pub(super) fn settled(&self) -> bool {
self.pending.is_empty()
}
fn moved_to(&mut self, at: f32, settled: bool) {
if at != self.offset {
let step = at - self.offset;
let step = if self.inverted { -step } else { step };
self.lead = next_lead(self.lead, step, self.viewport);
if (at - self.offset).abs() > PIN_SLACK {
self.moved_by_scroll = true;
}
self.offset = at;
self.dirty = true;
}
if let Some(pin) = &mut self.pin
&& settled
{
if (at - pin.at).abs() <= PIN_SLACK {
if pin.animating {
pin.animating = false;
self.dirty = true;
}
} else if !pin.animating {
self.pin = None;
}
}
}
pub(super) fn pin(&mut self, target: Option<PinTarget>, offset: f32, animated: bool) {
self.moved_by_scroll = true;
self.pin = target.map(|target| Pin {
target,
at: offset,
animating: animated,
});
}
pub(super) fn target_offset(&self, target: PinTarget) -> f32 {
match target {
PinTarget::End => self.end_offset(),
PinTarget::Index {
index,
view_position,
view_offset,
} => self.offset_for_index(index, view_position, view_offset),
}
}
pub(super) fn follow_pin(&mut self, anchored: f32) -> Follow {
let Some(mut pin) = self.pin else {
return Follow::Stay;
};
if self.viewport <= 0.0 {
return Follow::Stay;
}
let target = self.target_offset(pin.target);
if pin.animating {
pin.at += anchored;
let follow = if (target - pin.at).abs() > PIN_SLACK {
pin.at = target;
Follow::To(target)
} else {
Follow::Stay
};
self.pin = Some(pin);
return follow;
}
let delta = target - self.offset;
if delta != 0.0 {
self.jump(target);
}
pin.at = target;
self.pin = (!self.viewport_measured()).then_some(pin);
if delta == 0.0 {
Follow::Stay
} else {
Follow::By(delta)
}
}
#[cfg(test)]
pub(super) fn pinned(&self) -> bool {
self.pin.is_some()
}
fn viewport_measured(&self) -> bool {
let start = self.natural_offset();
self.items_in(start, start + self.viewport)
.is_none_or(|(first, last)| {
self.sizes[first as usize..=last as usize]
.iter()
.all(|s| !s.is_nan())
})
}
fn effective(&self, i: usize) -> f32 {
let s = self.sizes[i];
if s.is_nan() { self.estimated } else { s }
}
fn row_count(&self) -> u32 {
self.count.div_ceil(self.columns)
}
fn row_of(&self, i: u32) -> u32 {
i / self.columns
}
fn row_size(&self, r: u32) -> f32 {
let start = (r * self.columns) as usize;
let end = (start + self.columns as usize).min(self.sizes.len());
(start..end).map(|i| self.effective(i)).fold(0.0, f32::max)
}
fn main_gap(&self) -> f32 {
if self.horizontal {
self.content.column_gap.0
} else {
self.content.row_gap.0
}
}
pub(super) fn cross_gap(&self) -> f32 {
if self.horizontal {
self.content.row_gap.0
} else {
self.content.column_gap.0
}
}
fn main_padding(&self) -> (f32, f32) {
let p = &self.content.padding;
if self.horizontal && self.mirrored {
(p.right.0, p.left.0)
} else if self.horizontal {
(p.left.0, p.right.0)
} else {
(p.top.0, p.bottom.0)
}
}
pub(super) fn cross_padding(&self) -> (f32, f32) {
let p = &self.content.padding;
if self.horizontal {
(p.top.0, p.bottom.0)
} else {
(p.left.0, p.right.0)
}
}
fn rows_changed(&mut self) {
self.dirty = true;
}
fn rebuild_offsets(&mut self) {
let gap = self.main_gap() as f64;
let rows = (0..self.row_count()).map(|r| self.row_size(r) as f64 + gap);
self.rows = Fenwick::from_sizes(rows.collect::<Vec<_>>().into_iter());
self.dirty = true;
}
fn resize_rows(&mut self, old: u32) {
let columns = self.columns;
let old_rows = old.div_ceil(columns) as usize;
if self.rows.len() != old_rows {
self.rebuild_offsets();
return;
}
let rows = self.row_count() as usize;
let gap = self.main_gap() as f64;
let kept = old_rows.min(rows);
self.rows.truncate(kept);
if kept > 0 {
let last = kept - 1;
let now = self.row_size(last as u32) as f64 + gap;
let was = self.rows.prefix(kept) - self.rows.prefix(last);
if now != was {
self.rows.add(last, now - was);
}
}
for r in kept..rows {
self.rows.push(self.row_size(r as u32) as f64 + gap);
}
self.dirty = true;
}
fn items_len(&self) -> f32 {
if self.count == 0 {
0.0
} else {
self.rows.total() as f32 - self.main_gap()
}
}
pub(super) fn blocks(&self) -> Blocks {
let gap = self.main_gap();
let (start, end) = self.main_padding();
let [header, footer, empty] = &self.extras;
let mut at = start;
let mut any = false;
let mut place = |present: bool, size: f32| {
if !present {
return at;
}
if any {
at += gap;
}
any = true;
let here = at;
at += size;
here
};
let header_at = place(header.present(), header.size);
let body_at = if self.count > 0 {
place(true, self.items_len())
} else {
place(empty.present(), empty.size)
};
let footer_at = place(footer.present(), footer.size);
Blocks {
header: header_at,
body: body_at,
footer: footer_at,
total: at + end,
}
}
pub(super) fn content_len(&self) -> f32 {
let total = self.blocks().total;
if self.inverted || self.bottom() {
total.max(self.viewport)
} else {
total
}
}
pub(super) fn to_content(&self, at: f32, size: f32) -> f32 {
if self.inverted {
self.content_len() - at - size
} else {
at + self.leading()
}
}
fn natural_offset(&self) -> f32 {
if self.inverted {
self.content_len() - self.offset - self.viewport
} else {
self.offset - self.leading()
}
}
fn bottom(&self) -> bool {
self.alignment == ListAlignment::Bottom && !self.inverted
}
fn leading(&self) -> f32 {
if self.bottom() {
(self.viewport - self.blocks().total).max(0.0)
} else {
0.0
}
}
pub(super) fn item_at(&self, i: u32) -> f32 {
self.blocks().body + self.rows.prefix(self.row_of(i) as usize) as f32
}
pub(super) fn column(&self, cross: f32, col: u32, cell: Option<f32>) -> (f32, f32) {
let (start, end) = self.cross_padding();
let gap = self.cross_gap();
let n = self.columns as f32;
let mut width = ((cross - start - end - gap * (n - 1.0)) / n).max(0.0);
if let Some(cell) = cell.filter(|&c| c > 0.0) {
width = (width / cell + 1e-3).floor() * cell;
}
(start + col as f32 * (width + gap), width)
}
pub(super) fn full_width(&self, cross: f32) -> (f32, f32) {
let (start, end) = self.cross_padding();
(start, (cross - start - end).max(0.0))
}
pub(super) fn row_extent(&self, i: u32) -> f32 {
self.row_size(self.row_of(i))
}
pub(super) fn column_of(&self, i: u32) -> u32 {
i % self.columns
}
pub(super) fn set_count(&mut self, count: u32) {
if count == self.count {
return;
}
self.count = count;
self.items_changed = true;
for s in &mut self.slots {
if s.requested.is_some_and(|r| r >= count) {
s.requested = None;
s.rendered = None;
}
}
let old = self.sizes.len() as u32;
self.sizes.resize(count as usize, f32::NAN);
self.resize_rows(old);
if self.load_more_at.is_some_and(|c| c != count) {
self.load_more_at = None;
}
}
pub(super) fn set_estimated(&mut self, estimated: f32) {
if estimated > 0.0 && estimated != self.estimated {
let anchor = self.visible_anchor().filter(|_| !self.inverted);
self.estimated = estimated;
self.rebuild_offsets();
if let Some((index, from_top)) = anchor {
self.keep_in_place(index, from_top);
}
}
}
pub(super) fn set_columns(&mut self, columns: u32) {
let columns = columns.max(1);
if columns != self.columns {
let anchor = self.visible_anchor().filter(|_| !self.inverted).map(
|(index, from_top)| match self.columns_anchor {
Some(kept) if kept < self.count && self.row_of(kept) == self.row_of(index) => {
(kept, from_top)
}
_ => (index, from_top),
},
);
self.columns_anchor = anchor.map(|(index, _)| index);
self.columns = columns;
self.sizes.fill(f32::NAN);
self.cells_cross = f32::NAN;
self.rebuild_offsets();
if let Some((index, from_top)) = anchor {
self.keep_in_place(index, from_top);
}
}
}
pub(super) fn set_content(&mut self, content: ListContentStyle) {
self.content_style = content;
self.apply_content();
}
pub(super) fn set_class_content(&mut self, content: ListContentStyle) {
self.content_class = content;
self.apply_content();
}
fn apply_content(&mut self) {
let content = if self.content_style != ListContentStyle::default() {
self.content_style
} else {
self.content_class
};
if content != self.content {
let cross_changed = self.cross_padding() != {
let p = &content.padding;
if self.horizontal {
(p.top.0, p.bottom.0)
} else {
(p.left.0, p.right.0)
}
} || self.cross_gap()
!= if self.horizontal {
content.row_gap.0
} else {
content.column_gap.0
};
self.content = content;
if cross_changed {
self.cells_cross = f32::NAN;
}
self.rebuild_offsets();
}
}
pub(super) fn set_horizontal(&mut self, horizontal: bool) {
if horizontal != self.horizontal {
self.horizontal = horizontal;
self.sizes.fill(f32::NAN);
self.rebuild_offsets();
}
}
pub(super) fn set_mirrored(&mut self, mirrored: bool) {
if mirrored != self.mirrored {
self.mirrored = mirrored;
let p = &self.content.padding;
if self.horizontal && p.left != p.right {
self.rebuild_offsets();
}
}
}
pub(super) fn set_inverted(&mut self, inverted: bool) {
if self.parent {
self.ignored |= if inverted { ignored::INVERTED } else { 0 };
return;
}
if inverted != self.inverted {
self.inverted = inverted;
self.anchored_end = f32::NAN;
self.dirty = true;
}
}
pub(super) fn set_follow_end(&mut self, threshold: Option<f32>) {
if self.parent {
self.ignored |= if threshold.is_some() {
ignored::FOLLOW_END
} else {
0
};
return;
}
if threshold != self.follow_end {
self.follow_end = threshold;
self.anchored_end = f32::NAN;
self.dirty = true;
}
}
pub(super) fn set_alignment(&mut self, alignment: ListAlignment) {
if self.parent {
self.ignored |= if alignment == ListAlignment::Top {
0
} else {
ignored::ALIGNMENT
};
return;
}
if alignment != self.alignment {
self.alignment = alignment;
self.anchored_end = f32::NAN;
self.dirty = true;
}
}
pub(super) fn set_kept(&mut self, mut items: Vec<u32>) {
items.sort_unstable();
items.dedup();
if items != self.kept {
self.kept = items;
self.dirty = true;
}
}
pub(super) fn set_sticky(&mut self, mut sticky: Vec<u32>) {
sticky.sort_unstable();
sticky.dedup();
if sticky != self.sticky {
self.sticky = sticky;
self.dirty = true;
}
}
pub(super) fn set_sticky_node(&mut self, node: Option<crate::animation::NodeId>) {
if node != self.sticky_node {
self.sticky_node = node;
self.dirty = true;
}
}
pub(super) fn set_sticky_offset(&mut self, offset: f32) {
let offset = if offset.is_finite() { offset } else { 0.0 };
if offset != self.sticky_offset {
self.sticky_offset = offset;
self.dirty = true;
}
}
pub(super) fn measured(&mut self, i: u32, size: f32) -> f32 {
let idx = i as usize;
if idx >= self.sizes.len() || self.sizes[idx] == size {
return 0.0;
}
let row = self.row_of(i);
let before = self.row_size(row);
let row_start = self.item_at(i);
let natural = self.measuring_natural_offset();
let above_viewport = row_start < natural && row_start + before <= natural;
let keep = above_viewport && self.keeps_visible_rows_at(natural);
self.sizes[idx] = size;
let delta = self.row_size(row) - before;
if delta != 0.0 {
self.rows.add(row as usize, delta as f64);
}
self.dirty = true;
let scroll = self.before_viewport_changed(keep, delta, natural);
self.measured_scroll += scroll;
scroll
}
fn before_viewport_changed(&self, keep: bool, delta: f32, natural: f32) -> f32 {
match (keep, self.inverted) {
(false, _) => 0.0,
(true, false) => delta,
(true, true) => -delta.max(-natural),
}
}
pub(super) fn measured_extra(&mut self, kind: ExtraKind, size: f32) -> f32 {
let blocks = self.blocks();
let natural = self.measuring_natural_offset();
let keeps = self.keeps_visible_rows_at(natural);
let extra = &mut self.extras[kind as usize];
if extra.size == size {
return 0.0;
}
let delta = size - extra.size;
extra.size = size;
self.rows_changed();
let at = match kind {
ExtraKind::Header => blocks.header,
ExtraKind::Footer => blocks.footer,
ExtraKind::Empty => blocks.body,
};
let old_end = at + size - delta;
let keep = keeps && at < natural && old_end <= natural;
let scroll = self.before_viewport_changed(keep, delta, natural);
self.measured_scroll += scroll;
scroll
}
pub(super) fn anchor_end(&mut self, kept: f32) -> f32 {
self.measured_scroll = 0.0;
if self.viewport <= 0.0 {
return 0.0;
}
let end = (self.content_len() - self.viewport).max(0.0);
if !self.inverted {
let bottom = self.bottom();
let threshold = match self.follow_end {
Some(threshold) => threshold,
None if bottom => PIN_SLACK,
None => return 0.0,
};
if bottom && !self.anchored_end.is_nan() && self.last_row_being_measured() {
self.anchored_end += kept;
return 0.0;
}
let was = std::mem::replace(&mut self.anchored_end, end);
let opening = bottom && was.is_nan();
let distance = was - (self.offset - kept);
let settle = bottom && (0.0..=PIN_SLACK).contains(&distance);
if !opening && (was.is_nan() || distance > threshold || (end <= was && !settle)) {
return 0.0;
}
let delta = end - self.offset;
self.offset = end;
return delta;
}
let delta = if self.anchored_end.is_nan() {
end - self.offset
} else {
end - self.anchored_end
};
self.anchored_end = end;
self.offset += delta;
delta
}
fn last_row_being_measured(&self) -> bool {
let Some(last) = self.count.checked_sub(1) else {
return false;
};
self.sizes[last as usize].is_nan()
&& self.item_at(last) < self.natural_offset() + self.viewport * (1.0 + OVERSCAN)
}
pub(super) fn jump(&mut self, offset: f32) {
self.offset = offset;
if self.inverted {
self.anchored_end = (self.content_len() - self.viewport).max(0.0);
}
self.dirty = true;
}
pub(super) fn offset_for_index(&self, index: u32, view_position: f32, view_offset: f32) -> f32 {
let index = index.min(self.count.saturating_sub(1));
let size = self.row_size(self.row_of(index));
let at = self.to_content(self.item_at(index), size);
let free = self.viewport - size;
let offset = if self.inverted {
at - (1.0 - view_position) * free + view_offset
} else {
at - view_position * free - view_offset
};
let (min, max) = self.offset_limits();
offset.clamp(min, max)
}
pub(super) fn end_offset(&self) -> f32 {
if self.inverted {
0.0
} else if self.parent {
let (min, max) = self.limits;
(self.content_len() - self.viewport).clamp(min, max)
} else {
(self.content_len() - self.viewport).max(0.0)
}
}
pub(super) fn add_slot_cell(&mut self, slot: CellSlot, cell: u32) {
let s = match slot {
CellSlot::Item(s) => s as usize,
CellSlot::Header => return self.set_extra(ExtraKind::Header, cell),
CellSlot::Footer => return self.set_extra(ExtraKind::Footer, cell),
CellSlot::Empty => return self.set_extra(ExtraKind::Empty, cell),
};
if s >= self.slots.len() {
self.slots.resize(
s + 1,
Slot {
cell: u32::MAX,
index: None,
rendered: None,
requested: None,
},
);
}
self.slots[s].cell = cell;
self.dirty = true;
}
fn set_extra(&mut self, kind: ExtraKind, cell: u32) {
self.extras[kind as usize] = Extra { cell, size: 0.0 };
self.dirty = true;
}
pub(super) fn frees(&self, cell: u32) -> bool {
self.slots
.iter()
.any(|s| s.cell == cell && s.index.is_none())
}
pub(super) fn remove_cell(&mut self, cell: u32) {
for slot in &mut self.slots {
if slot.cell == cell {
slot.cell = u32::MAX;
slot.rendered = None;
slot.requested = None;
self.dirty = true;
}
}
for extra in &mut self.extras {
if extra.cell == cell {
*extra = Extra::NONE;
self.dirty = true;
}
}
}
pub(super) fn rendered(&mut self, cell: u32, index: u32) {
if let Some(slot) = self.slots.iter_mut().find(|s| s.cell == cell) {
slot.rendered = Some(index);
self.dirty = true;
}
}
fn items_in(&self, start: f32, end: f32) -> Option<(u32, u32)> {
if self.count == 0 {
return None;
}
let body = self.blocks().body;
if end < body || start > body + self.items_len() {
return None;
}
let first_row = self.rows.find((start - body).max(0.0) as f64) as u32;
let last_row =
(self.rows.find((end - body).max(0.0) as f64) as u32).min(self.row_count() - 1);
let first = first_row * self.columns;
let last = ((last_row + 1) * self.columns - 1).min(self.count - 1);
Some((first, last))
}
pub(super) fn render_window(&self) -> (f32, f32) {
let overscan = self.viewport * OVERSCAN;
(
self.offset - overscan,
self.offset + self.viewport + overscan,
)
}
pub(super) fn active_sticky(&self) -> Option<u32> {
if !self.sticky_enabled() {
return None;
}
let at = self.natural_offset() + self.sticky_offset;
let mut active = None;
for &s in &self.sticky {
if s >= self.count || self.item_at(s) > at {
break;
}
active = Some(s);
}
active
}
pub(super) fn sticky_enabled(&self) -> bool {
!self.sticky.is_empty() && self.columns == 1 && !self.inverted
}
pub(super) fn sticky_range(&self, index: u32, cell: u32, size: f32) -> StickyRange {
let start = self.item_at(index) - self.sticky_offset;
let next = self
.sticky
.get(self.sticky.partition_point(|&s| s <= index))
.filter(|&&s| s < self.count);
let end = match next {
Some(&n) => (self.item_at(n) - size - self.sticky_offset).max(start),
None if self.parent => {
let end = self.blocks().total - self.main_padding().1;
(end - size - self.sticky_offset).max(start)
}
None => f32::INFINITY,
};
if self.parent {
let at = self.outer_start;
return StickyRange {
cell,
start: at + start,
end: at + end,
offset: self.sticky_node,
};
}
StickyRange {
cell,
start,
end,
offset: self.sticky_node,
}
}
pub(super) fn update_window(&mut self, binds: &mut Vec<(u32, u32)>) -> Edges {
self.dirty = false;
binds.append(&mut self.moved);
if self.count == 0 || self.viewport <= 0.0 {
for slot in 0..self.slots.len() {
self.unbind(slot as u32);
}
return Edges::default();
}
let at = self.natural_offset();
let overscan = self.viewport * OVERSCAN;
let range = self.items_in(at - overscan, at + self.viewport + overscan);
let sticky = self.active_sticky();
let before = sticky.and_then(|s| {
self.sticky[..self.sticky.partition_point(|&p| p < s)]
.last()
.copied()
});
let kept = std::mem::take(&mut self.kept);
let wanted = |i: u32| {
range.is_some_and(|(f, l)| (f..=l).contains(&i))
|| sticky == Some(i)
|| before == Some(i)
|| kept.contains(&i)
};
for slot in 0..self.slots.len() as u32 {
if let Some(i) = self.slots[slot as usize].index
&& !wanted(i)
{
self.unbind(slot);
}
}
let bind = |this: &mut Self, i: u32, own: bool| {
if this.by_index.contains_key(&i) {
return;
}
let slots = &this.slots;
let shows = |s: &u32| {
let s = &slots[*s as usize];
s.rendered == Some(i) && s.requested == Some(i)
};
let own_slot = this.free.iter().rposition(shows);
let slot = match own_slot {
Some(at) => this.free.remove(at),
None if own => return,
None => match this.free.pop() {
Some(slot) => slot,
None => {
this.slots.push(Slot {
cell: u32::MAX,
index: None,
rendered: None,
requested: None,
});
this.slots.len() as u32 - 1
}
},
};
this.slots[slot as usize].index = Some(i);
this.by_index.insert(i, slot);
};
let count = self.count;
let passes: &[bool] = if self.free.is_empty() {
&[false]
} else {
&[true, false]
};
for &own in passes {
if let Some((first, last)) = range {
for i in first..=last {
bind(self, i, own);
}
}
for s in [before, sticky].into_iter().flatten() {
bind(self, s, own);
}
for &i in kept.iter().filter(|&&i| i < count) {
bind(self, i, own);
}
}
let (start, end) = self.urgent_span(at);
let new = binds.len();
for slot in 0..self.slots.len() {
let s = self.slots[slot];
let Some(i) = s.index else { continue };
if s.requested == Some(i) {
continue;
}
if !self.paced
|| sticky == Some(i)
|| before == Some(i)
|| kept.contains(&i)
|| self.item_overlaps(i, start, end)
{
self.slots[slot].requested = Some(i);
binds.push((slot as u32, i));
}
}
binds[new..].sort_unstable_by_key(|b| b.1);
self.kept = kept;
let total = self.blocks().total;
let near_end = at + self.viewport >= total - self.viewport * self.end_threshold;
let mut edges = Edges::default();
if near_end && self.load_more_at != Some(self.count) {
self.load_more_at = Some(self.count);
edges.end = true;
}
let near_start = at <= self.viewport * self.start_threshold;
if !near_start {
self.load_more_at_start = None;
} else if self.moved_by_scroll && self.load_more_at_start != Some(self.count) {
self.load_more_at_start = Some(self.count);
edges.start = true;
}
edges
}
fn urgent_span(&self, at: f32) -> (f32, f32) {
let step = self.lead.abs();
let ahead = if step <= self.viewport {
(URGENT_STEPS * step).min(self.viewport * OVERSCAN)
} else {
0.0
};
if self.lead > 0.0 {
(at, at + self.viewport + ahead)
} else {
(at - ahead, at + self.viewport)
}
}
fn item_overlaps(&self, i: u32, start: f32, end: f32) -> bool {
let top = self.item_at(i);
top < end && top + self.row_size(self.row_of(i)) > start
}
pub(super) fn has_paced(&self) -> bool {
self.slots
.iter()
.any(|s| s.index.is_some() && s.index != s.requested)
}
pub(super) fn take_paced(&mut self, max: usize, binds: &mut Vec<(u32, u32)>) -> usize {
let mut taken = 0;
while taken < max {
let Some((slot, i)) = self.nearest_waiting() else {
break;
};
self.slots[slot as usize].requested = Some(i);
binds.push((slot, i));
taken += 1;
}
taken
}
fn nearest_waiting(&self) -> Option<(u32, u32)> {
let at = self.natural_offset();
let (top, bottom) = (at, at + self.viewport);
let forward = self.lead >= 0.0;
let mut best: Option<((bool, f32), u32, u32)> = None;
for (slot, s) in self.slots.iter().enumerate() {
let Some(i) = s.index else { continue };
if s.requested == Some(i) {
continue;
}
let start = self.item_at(i);
let (distance, below) = if start >= bottom {
(start - bottom, true)
} else {
let end = start + self.row_size(self.row_of(i));
((top - end).max(0.0), false)
};
let key = (below != forward, distance);
if best.is_none_or(|(b, ..)| key.0.cmp(&b.0).then(key.1.total_cmp(&b.1)).is_lt()) {
best = Some((key, slot as u32, i));
}
}
best.map(|(_, slot, i)| (slot, i))
}
fn unbind(&mut self, slot: u32) {
if let Some(i) = self.slots[slot as usize].index.take() {
self.by_index.remove(&i);
self.free.push(slot);
}
}
pub(super) fn viewable_items(&self) -> Option<(u32, u32)> {
if self.viewport <= 0.0 {
return None;
}
let top = self.natural_offset();
let bottom = top + self.viewport;
let (first, last) = self.items_in(top, bottom)?;
let viewable = |row: u32| {
let start = self.item_at(row * self.columns);
let size = self.row_size(row);
let end = start + size;
if start >= top && end <= bottom {
return true;
}
let pixels = (end.min(bottom) - start.max(top)).max(0.0);
let (share, threshold) = match (
self.viewability.view_area_coverage_threshold,
self.viewability.item_visible_threshold,
) {
(Some(t), _) => (pixels / self.viewport, t.0),
(None, Some(t)) => (pixels / size.max(f32::EPSILON), t.0),
(None, None) => return pixels > 0.0,
};
if threshold > 0.0 {
share >= threshold
} else {
pixels > 0.0
}
};
let (mut first_row, mut last_row) = (self.row_of(first), self.row_of(last));
while first_row <= last_row && !viewable(first_row) {
first_row += 1;
}
while last_row >= first_row && !viewable(last_row) {
if last_row == 0 {
return None;
}
last_row -= 1;
}
(first_row <= last_row).then(|| {
(
first_row * self.columns,
((last_row + 1) * self.columns - 1).min(self.count - 1),
)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
geometry::{Percentage, px},
props::EdgeInsets,
};
fn list(count: u32, estimated: f32, viewport: f32) -> ListState {
let mut l = ListState::new();
l.set_estimated(estimated);
l.set_count(count);
l.viewport = viewport;
l
}
#[test]
fn appending_and_dropping_rows_matches_a_rebuild() {
for columns in [1, 3] {
let mut l = list(0, 30.0, 400.0);
l.set_columns(columns);
l.content.row_gap = px(4.0);
let check = |l: &mut ListState| {
let rows = l.rows.clone();
l.rebuild_offsets();
assert_eq!(rows.len(), l.rows.len());
for r in 0..=rows.len() {
assert!((rows.prefix(r) - l.rows.prefix(r)).abs() < 1e-6, "row {r}");
}
};
for c in 1..40 {
l.set_count(c);
l.measured(c - 1, 20.0 + (c % 5) as f32 * 7.0);
check(&mut l);
}
for _ in 0..10 {
l.splice(l.count, 0, 2);
check(&mut l);
}
for c in [55, 31, 30, 7, 0, 5] {
l.set_count(c);
check(&mut l);
}
}
}
#[test]
fn window_covers_viewport_plus_overscan() {
let mut l = list(1000, 50.0, 400.0);
let mut binds = Vec::new();
l.update_window(&mut binds);
assert_eq!(binds.len(), 17);
assert_eq!(binds[0], (0, 0));
l.offset = 2000.0;
binds.clear();
l.update_window(&mut binds);
let indices: Vec<u32> = binds.iter().map(|b| b.1).collect();
assert_eq!(indices.first(), Some(&32));
assert_eq!(indices.last(), Some(&56));
assert!(l.slots.len() <= 25 + 17, "{}", l.slots.len());
}
#[test]
fn measurements_shift_offsets_and_anchor_above_viewport() {
let mut l = list(100, 50.0, 400.0);
l.offset = 1000.0;
assert_eq!(l.measured(0, 80.0), 30.0);
assert_eq!(l.item_at(1), 80.0);
assert_eq!(l.blocks().total, 100.0 * 50.0 + 30.0);
assert_eq!(l.measured(30, 10.0), 0.0);
}
#[test]
fn load_more_fires_once_per_count() {
let mut l = list(10, 50.0, 400.0);
let mut binds = Vec::new();
assert!(
l.update_window(&mut binds).end,
"500 px of content in a 400 px viewport"
);
assert!(!l.update_window(&mut binds).end);
l.set_count(20);
l.offset = 600.0;
assert!(l.update_window(&mut binds).end);
}
#[test]
fn load_more_at_start_fires_once_per_approach_after_a_scroll() {
let mut l = list(100, 50.0, 400.0);
let mut binds = Vec::new();
assert!(!l.update_window(&mut binds).start);
l.reported(2000.0, 0);
assert!(!l.update_window(&mut binds).start);
l.reported(300.0, 0);
assert!(l.update_window(&mut binds).start);
l.reported(100.0, 0);
assert!(!l.update_window(&mut binds).start);
l.splice(0, 0, 2);
assert_eq!(l.offset, 200.0);
assert!(l.update_window(&mut binds).start);
assert!(!l.update_window(&mut binds).start);
l.reported(1500.0, 0);
assert!(!l.update_window(&mut binds).start);
l.reported(0.0, 0);
assert!(l.update_window(&mut binds).start);
let mut t = list(100, 50.0, 400.0);
t.start_threshold = 0.25;
t.reported(150.0, 0);
assert!(!t.update_window(&mut binds).start);
t.reported(100.0, 0);
assert!(t.update_window(&mut binds).start);
}
#[test]
fn load_more_at_start_fires_where_a_scroll_command_lands() {
let mut l = list(100, 50.0, 400.0);
let target = PinTarget::Index {
index: 2,
view_position: 0.0,
view_offset: 0.0,
};
let offset = l.target_offset(target);
l.pin(Some(target), offset, false);
l.jump(offset);
let mut binds = Vec::new();
assert!(l.update_window(&mut binds).start);
}
#[test]
fn bottom_aligned_lists_stay_at_their_end_as_rows_above_are_measured() {
let mut l = list(100, 50.0, 400.0);
l.set_alignment(ListAlignment::Bottom);
l.anchor_end(0.0);
let end = l.content_len() - 400.0;
assert_eq!(l.offset, end);
let kept = l.measured(50, 30.0);
assert_eq!(kept, -20.0);
assert_eq!(l.measured(99, 70.0), 0.0);
l.offset += kept;
let scroll = l.anchor_end(kept);
assert_eq!(l.content_len() - 400.0, end);
assert_eq!(kept + scroll, 0.0);
assert_eq!(l.offset, end);
l.splice(100, 0, 1);
l.take_splice_anchor();
let kept = l.measured(51, 30.0);
l.offset += kept;
assert_eq!(l.anchor_end(kept), 0.0, "waits for the row's real size");
l.measured(100, 34.0);
assert_eq!(l.anchor_end(0.0), 34.0);
assert_eq!(l.offset, l.content_len() - 400.0);
let up = l.content_len() - 400.0 - 500.0;
l.reported(up, 0);
let kept = l.measured(52, 30.0);
l.offset += kept;
assert_eq!(l.anchor_end(kept), 0.0);
assert_eq!(l.offset, up + kept);
}
#[test]
fn bottom_aligned_lists_rest_at_their_end() {
let on_screen = |l: &ListState, i: u32| l.to_content(l.item_at(i), 50.0) - l.offset;
let mut l = list(100, 50.0, 400.0);
l.set_alignment(ListAlignment::Bottom);
assert_eq!(l.anchor_end(0.0), 4600.0);
let mut binds = Vec::new();
l.update_window(&mut binds);
assert!(binds.iter().any(|&(_, i)| i == 99));
assert!(!binds.iter().any(|&(_, i)| i == 0));
let row = l.to_content(l.item_at(90), 50.0);
l.splice(100, 0, 1);
assert_eq!(l.take_splice_anchor(), 0.0);
assert_eq!(l.anchor_end(0.0), 0.0, "waits for the row's real size");
assert_eq!(l.measured(100, 34.0), 0.0);
assert_eq!(l.anchor_end(0.0), 34.0);
assert_eq!(l.to_content(l.item_at(90), 50.0), row);
let anchor = l.measured(100, 80.0);
assert_eq!(anchor + l.anchor_end(0.0), 46.0);
assert_eq!(l.to_content(l.item_at(90), 50.0), row);
let before = on_screen(&l, 95);
l.splice(0, 0, 10);
let scrolled = l.take_splice_anchor();
assert_eq!(scrolled, 500.0);
assert_eq!(l.anchor_end(0.0), 0.0);
assert_eq!(on_screen(&l, 105), before);
let end = l.content_len() - 400.0;
l.reported(end - 500.0, 0);
l.splice(l.count, 0, 1);
l.take_splice_anchor();
assert_eq!(l.anchor_end(0.0), 0.0);
l.measured(l.count - 1, 50.0);
l.anchor_end(0.0);
l.reported(l.content_len() - 400.0, 0);
l.splice(l.count, 0, 1);
l.take_splice_anchor();
assert_eq!(l.anchor_end(0.0), 0.0);
l.measured(l.count - 1, 50.0);
assert_eq!(l.anchor_end(0.0), 50.0);
l.splice(l.count, 0, 100);
assert_eq!(l.anchor_end(0.0), 5000.0);
}
#[test]
fn bottom_aligned_list_preserves_native_bottom_bounce() {
let mut l = list(20, 50.0, 400.0);
l.set_alignment(ListAlignment::Bottom);
l.follow_end = Some(80.0);
for i in 0..20 {
l.measured(i, 50.0);
}
l.anchor_end(0.0);
for overshoot in [0.25, 10.0, 30.0, 60.0, 30.0, 10.0, 0.25, 0.0] {
l.reported(600.0 + overshoot, 0);
assert_eq!(l.anchor_end(0.0), 0.0, "overshoot {overshoot}");
assert_eq!(l.offset, 600.0 + overshoot);
}
}
#[test]
fn bottom_aligned_lists_keep_short_content_at_the_bottom() {
let mut l = list(2, 50.0, 400.0);
l.set_alignment(ListAlignment::Bottom);
assert_eq!(l.anchor_end(0.0), 0.0);
assert_eq!(l.content_len(), 400.0);
assert_eq!(l.to_content(l.item_at(0), 50.0), 300.0);
assert_eq!(l.to_content(l.item_at(1), 50.0), 350.0);
let mut binds = Vec::new();
l.update_window(&mut binds);
assert_eq!(binds.len(), 2);
l.splice(2, 0, 1);
assert_eq!(l.anchor_end(0.0), 0.0);
assert_eq!(l.to_content(l.item_at(0), 50.0), 250.0);
}
#[test]
fn inverted_lists_load_at_their_start_and_keep_the_visible_rows() {
let mut l = list(100, 50.0, 400.0);
l.set_inverted(true);
l.loads_at_start = true;
l.anchor_end(0.0);
let mut binds = Vec::new();
assert!(!l.update_window(&mut binds).start);
l.reported(5000.0 - 400.0 - 1000.0, 0);
assert!(!l.update_window(&mut binds).start);
l.reported(5000.0 - 400.0 - 200.0, 0);
assert!(l.update_window(&mut binds).start);
let on_screen = |l: &ListState, i: u32| l.to_content(l.item_at(i), 50.0) - l.offset;
let before = on_screen(&l, 4);
l.splice(0, 0, 4);
let scrolled = l.take_splice_anchor() + l.anchor_end(0.0);
assert_eq!(scrolled, 0.0);
assert_eq!(on_screen(&l, 8), before);
let offset = l.offset;
let anchor = l.measured(0, 80.0);
l.offset += anchor;
assert_eq!(anchor + l.anchor_end(0.0), 0.0);
assert_eq!(l.offset, offset);
let mut c = list(100, 50.0, 400.0);
c.set_inverted(true);
c.loads_at_start = true;
c.anchor_end(0.0);
c.splice(0, 0, 1);
c.take_splice_anchor();
c.anchor_end(0.0);
assert_eq!(c.natural_offset(), 0.0);
let mut d = list(100, 50.0, 400.0);
d.set_inverted(true);
d.anchor_end(0.0);
d.reported(5000.0 - 400.0 - 200.0, 0);
d.splice(0, 0, 4);
assert_eq!(d.take_splice_anchor(), 0.0);
d.anchor_end(0.0);
assert_eq!(d.natural_offset(), 200.0);
}
#[test]
fn shrinking_count_unbinds() {
let mut l = list(100, 50.0, 400.0);
let mut binds = Vec::new();
l.update_window(&mut binds);
l.set_count(3);
binds.clear();
l.update_window(&mut binds);
assert_eq!(l.slots.iter().filter(|s| s.index.is_some()).count(), 3);
}
#[test]
fn a_terminal_s_columns_are_whole_equal_cells() {
let mut l = list(90, 50.0, 1000.0);
l.set_columns(9);
l.content.padding.left = crate::Points(8.0);
l.content.padding.right = crate::Points(8.0);
l.content.column_gap = crate::Points(16.0);
assert_eq!(l.column(1360.0, 1, Some(8.0)), (8.0 + 128.0 + 16.0, 128.0));
let (x, width) = l.column(1360.0, 8, Some(8.0));
assert!(x + width <= 1360.0 - 8.0, "the last inside the padding");
}
#[test]
fn columns_share_rows() {
let mut l = list(10, 50.0, 1000.0);
l.set_columns(3);
assert_eq!(l.blocks().total, 200.0);
assert_eq!(l.item_at(4), 50.0);
assert_eq!(l.column_of(4), 1);
l.measured(4, 80.0);
assert_eq!(l.item_at(6), 130.0);
assert_eq!(l.column(320.0, 2, None), (320.0 * 2.0 / 3.0, 320.0 / 3.0));
let mut binds = Vec::new();
l.update_window(&mut binds);
assert_eq!(binds.len(), 10);
}
#[test]
fn a_mirrored_horizontal_list_keeps_its_left_padding_on_the_left() {
let mut l = list(3, 50.0, 1000.0);
l.set_horizontal(true);
l.set_content(ListContentStyle {
padding: EdgeInsets {
left: px(16.0),
..EdgeInsets::default()
},
..ListContentStyle::default()
});
assert_eq!(l.blocks().body, 16.0);
l.set_mirrored(true);
assert_eq!(l.blocks().body, 0.0);
assert_eq!(l.blocks().total, 3.0 * 50.0 + 16.0);
}
#[test]
fn padding_gaps_and_extras() {
let mut l = list(3, 50.0, 1000.0);
l.set_content(ListContentStyle {
padding: EdgeInsets {
top: px(10.0),
right: px(16.0),
bottom: px(20.0),
left: px(16.0),
},
row_gap: px(8.0),
column_gap: px(0.0),
});
l.add_slot_cell(CellSlot::Header, 7);
l.measured_extra(ExtraKind::Header, 30.0);
l.add_slot_cell(CellSlot::Footer, 8);
l.measured_extra(ExtraKind::Footer, 40.0);
let b = l.blocks();
assert_eq!(b.header, 10.0);
assert_eq!(b.body, 10.0 + 30.0 + 8.0);
assert_eq!(b.footer, b.body + 3.0 * 50.0 + 2.0 * 8.0 + 8.0);
assert_eq!(b.total, b.footer + 40.0 + 20.0);
assert_eq!(l.full_width(400.0), (16.0, 368.0));
l.set_count(0);
l.add_slot_cell(CellSlot::Empty, 9);
l.measured_extra(ExtraKind::Empty, 100.0);
let b = l.blocks();
assert_eq!(b.footer, b.body + 100.0 + 8.0);
}
#[test]
fn the_scroll_position_is_the_row_at_the_viewports_start_and_the_depth_into_it() {
assert_eq!(list(0, 50.0, 400.0).scroll_position(), None);
let mut l = list(100, 50.0, 400.0);
l.set_content(ListContentStyle {
row_gap: px(8.0),
..ListContentStyle::default()
});
l.add_slot_cell(CellSlot::Header, 7);
l.measured_extra(ExtraKind::Header, 30.0);
assert_eq!(l.scroll_position(), Some((0, -38.0)));
l.measured(1, 90.0);
l.offset = 38.0 + 58.0 + 98.0 + 5.0;
assert_eq!(l.scroll_position(), Some((2, 5.0)));
l.offset = 38.0 + 58.0 + 98.0 + 52.0;
assert_eq!(l.scroll_position(), Some((2, 52.0)));
l.set_columns(3);
l.offset = 38.0 + 58.0 + 10.0;
assert_eq!(l.scroll_position(), Some((3, 10.0)));
let mut l = list(100, 50.0, 400.0);
l.set_inverted(true);
l.anchor_end(0.0);
assert_eq!(l.scroll_position(), Some((0, 0.0)));
l.offset -= 120.0;
assert_eq!(l.scroll_position(), Some((2, 20.0)));
}
#[test]
fn lists_follow_the_end_within_the_threshold() {
let mut l = list(100, 50.0, 400.0);
l.set_follow_end(Some(10.0));
assert_eq!(l.anchor_end(0.0), 0.0, "starts where it is");
l.offset = 5000.0 - 400.0;
l.measured(99, 80.0);
assert_eq!(l.anchor_end(0.0), 30.0);
assert_eq!(l.offset, 5030.0 - 400.0);
l.offset = 1000.0;
l.measured(99, 120.0);
assert_eq!(l.anchor_end(0.0), 0.0);
assert_eq!(l.offset, 1000.0);
let mut m = list(100, 50.0, 400.0);
m.anchor_end(0.0);
m.offset = 5000.0 - 400.0;
m.measured(99, 80.0);
assert_eq!(m.anchor_end(0.0), 0.0);
}
#[test]
fn inverted_lists_start_at_the_end_and_keep_their_distance_from_it() {
let mut l = list(100, 50.0, 400.0);
l.set_inverted(true);
assert_eq!(l.anchor_end(0.0), 5000.0 - 400.0);
assert_eq!(l.to_content(l.item_at(0), 50.0), 4950.0);
let mut binds = Vec::new();
l.update_window(&mut binds);
assert_eq!(binds.first().map(|b| b.1), Some(0));
assert!(binds.iter().all(|b| b.1 <= 16));
l.set_count(120);
assert_eq!(l.anchor_end(0.0), 1000.0);
assert_eq!(l.offset, 5600.0);
assert_eq!(l.to_content(l.item_at(0), 50.0), 5950.0);
let mut s = list(2, 50.0, 400.0);
s.set_inverted(true);
s.anchor_end(0.0);
assert_eq!(s.offset, 0.0);
assert_eq!(s.to_content(s.item_at(0), 50.0), 350.0);
}
#[test]
fn sticky_items_stick_at_their_offset() {
let mut l = list(100, 50.0, 400.0);
l.set_sticky(vec![0, 30]);
l.set_sticky_offset(20.0);
assert_eq!(
l.sticky_range(0, 1, 50.0),
StickyRange {
cell: 1,
start: -20.0,
end: 1430.0,
offset: None,
}
);
assert_eq!(l.sticky_range(30, 2, 50.0).start, 1480.0);
l.offset = 1470.0;
assert_eq!(l.active_sticky(), Some(0));
l.offset = 1480.0;
assert_eq!(l.active_sticky(), Some(30));
l.set_sticky_offset(0.0);
assert_eq!(l.sticky_range(0, 1, 50.0).start, 0.0);
assert_eq!(l.active_sticky(), Some(0));
l.set_sticky_offset(-10.0);
assert_eq!(l.sticky_range(30, 2, 50.0).start, 1510.0);
}
#[test]
fn sticky_items_stay_rendered_and_travel_until_the_next() {
let mut l = list(100, 50.0, 400.0);
l.set_sticky(vec![30, 0]);
l.offset = 1000.0;
assert_eq!(l.active_sticky(), Some(0));
let mut binds = Vec::new();
l.update_window(&mut binds);
assert!(binds.iter().any(|b| b.1 == 0), "{binds:?}");
assert_eq!(
l.sticky_range(0, 1, 50.0),
StickyRange {
cell: 1,
start: 0.0,
end: 1450.0,
offset: None,
}
);
assert_eq!(l.sticky_range(30, 1, 50.0).end, f32::INFINITY);
l.offset = 1600.0;
assert_eq!(l.active_sticky(), Some(30));
}
#[test]
fn the_sticky_item_before_the_pinned_one_stays_rendered() {
let mut l = list(100, 50.0, 400.0);
l.set_sticky(vec![0, 30, 60]);
l.offset = 3200.0;
assert_eq!(l.active_sticky(), Some(60));
let mut binds = Vec::new();
l.update_window(&mut binds);
let bound = |l: &ListState, i: u32| l.slots.iter().any(|s| s.index == Some(i));
assert!(bound(&l, 60) && bound(&l, 30), "{binds:?}");
assert!(!bound(&l, 0));
l.offset = 2000.0;
binds.clear();
l.update_window(&mut binds);
assert!(bound(&l, 30) && bound(&l, 0), "{binds:?}");
assert!(!bound(&l, 60));
}
#[test]
fn viewability_thresholds() {
let mut l = list(100, 100.0, 400.0);
l.offset = 50.0;
assert_eq!(l.viewable_items(), Some((0, 4)));
l.viewability.item_visible_threshold = Some(Percentage(0.6));
assert_eq!(l.viewable_items(), Some((1, 3)));
l.viewability.item_visible_threshold = Some(Percentage(0.5));
assert_eq!(l.viewable_items(), Some((0, 4)));
}
#[test]
fn stale_offset_reports_keep_pending_scrolls() {
let mut l = list(100, 50.0, 400.0);
l.offset = 500.0;
l.issue_scroll_by(30.0);
l.reported(500.0, 0);
assert_eq!(l.offset, 530.0);
l.issue_scroll_to(1000.0);
l.reported(531.0, 1);
assert_eq!(l.offset, 1000.0);
l.reported(1002.0, 2);
assert_eq!(l.offset, 1002.0);
assert!(l.pending.is_empty());
}
#[test]
fn extras_at_the_top_do_not_scroll_the_list() {
let mut l = list(0, 50.0, 400.0);
l.add_slot_cell(CellSlot::Empty, 3);
assert_eq!(l.measured_extra(ExtraKind::Empty, 65.0), 0.0);
let mut l = list(100, 50.0, 400.0);
l.add_slot_cell(CellSlot::Header, 3);
assert_eq!(l.measured_extra(ExtraKind::Header, 30.0), 0.0);
l.offset = 500.0;
assert_eq!(l.measured_extra(ExtraKind::Header, 40.0), 10.0);
l.set_inverted(true);
assert_eq!(l.measured_extra(ExtraKind::Header, 50.0), 0.0);
}
#[test]
fn splices_keep_measurements_cells_and_the_visible_content() {
let mut l = list(100, 50.0, 400.0);
let mut binds = Vec::new();
l.offset = 1000.0;
l.update_window(&mut binds);
for (slot, index) in binds.drain(..) {
l.add_slot_cell(CellSlot::Item(slot), 100 + slot);
l.rendered(100 + slot, index);
}
l.measured(25, 80.0);
let before = l.item_at(20) - l.offset;
l.splice(0, 0, 3);
assert_eq!(l.count, 103);
assert_eq!(l.item_at(23) - l.offset, before);
assert_eq!(l.take_splice_anchor(), 150.0);
assert_eq!(l.row_extent(28), 80.0);
l.update_window(&mut binds);
assert!(binds.iter().any(|&(_, i)| i == 28));
assert!(l.slots.iter().any(|s| s.ready() == Some(28)));
let offset = l.offset;
l.splice(90, 2, 0);
assert_eq!(l.offset, offset);
assert_eq!(l.count, 101);
}
#[test]
fn a_change_of_columns_keeps_the_first_visible_item_in_place() {
let mut l = list(90, 50.0, 400.0);
l.set_columns(9);
l.offset = 200.0;
assert_eq!(l.item_at(36) - l.offset, 0.0);
l.set_columns(5);
assert_eq!(l.item_at(36), 350.0);
assert_eq!(l.offset, 350.0);
assert_eq!(l.take_splice_anchor(), 150.0);
l.set_columns(9);
assert_eq!(l.offset, 200.0);
l.set_columns(7);
l.set_columns(4);
l.set_columns(9);
assert_eq!(l.offset, 200.0);
l.set_estimated(60.0);
assert_eq!(l.offset, 240.0);
l.set_estimated(50.0);
l.offset = 100.0;
l.set_columns(5);
assert_eq!(l.offset, 50.0 * (18 / 5) as f32);
let mut l = list(90, 50.0, 400.0);
l.set_columns(9);
l.set_columns(5);
assert_eq!(l.offset, 0.0);
}
#[test]
fn paced_lists_bind_the_viewport_now_and_the_overscan_ahead_first() {
let mut l = list(1000, 50.0, 400.0);
l.paced = true;
let mut binds = Vec::new();
l.update_window(&mut binds);
let now: Vec<u32> = binds.iter().map(|b| b.1).collect();
assert_eq!(now, (0..8).collect::<Vec<_>>(), "the viewport");
assert!(l.has_paced());
binds.clear();
assert_eq!(l.take_paced(3, &mut binds), 3);
assert_eq!(binds.iter().map(|b| b.1).collect::<Vec<_>>(), [8, 9, 10]);
while l.take_paced(100, &mut binds) > 0 {}
assert!(!l.has_paced());
l.reported(2000.0, 0);
l.update_window(&mut binds);
while l.take_paced(100, &mut binds) > 0 {}
l.reported(1950.0, 0);
binds.clear();
l.update_window(&mut binds);
assert_eq!(binds, []);
l.reported(5000.0, 0);
l.update_window(&mut binds);
let now: Vec<u32> = binds.iter().map(|b| b.1).collect();
assert_eq!(now, (100..108).collect::<Vec<_>>());
l.reported(4975.0, 0);
binds.clear();
l.update_window(&mut binds);
let now: Vec<u32> = binds.iter().map(|b| b.1).collect();
assert_eq!(now, (97..100).collect::<Vec<_>>());
binds.clear();
l.take_paced(3, &mut binds);
assert_eq!(binds.iter().map(|b| b.1).collect::<Vec<_>>(), [96, 95, 94]);
}
#[test]
fn a_fast_step_keeps_the_rows_ahead_binding_through_slow_ones() {
assert_eq!(next_lead(0.0, 80.0, 400.0), 80.0);
assert_eq!(next_lead(80.0, 20.0, 400.0), 60.0);
assert_eq!(next_lead(60.0, 100.0, 400.0), 100.0);
assert_eq!(next_lead(100.0, -20.0, 400.0), -20.0);
assert_eq!(next_lead(-20.0, -10.0, 400.0), -15.0);
assert_eq!(next_lead(3000.0, 20.0, 400.0), 20.0);
let mut l = list(1000, 50.0, 400.0);
l.paced = true;
let mut binds = Vec::new();
l.reported(1000.0, 0);
l.update_window(&mut binds);
while l.take_paced(100, &mut binds) > 0 {}
l.reported(1100.0, 0);
l.update_window(&mut binds);
l.reported(1110.0, 0);
binds.clear();
l.update_window(&mut binds);
assert!(binds.is_empty(), "{binds:?}");
assert_eq!(l.urgent_span(l.natural_offset()), (1110.0, 1810.0));
}
#[test]
fn a_list_at_its_start_shows_the_rows_inserted_above_the_first() {
let mut l = list(10, 50.0, 400.0);
l.splice(0, 0, 3);
assert_eq!((l.offset, l.take_splice_anchor()), (0.0, 0.0));
l.offset = 100.0;
l.splice(0, 0, 2);
assert_eq!((l.offset, l.take_splice_anchor()), (200.0, 100.0));
let mut l = list(10, 50.0, 400.0);
l.loads_at_start = true;
l.splice(0, 0, 3);
assert_eq!((l.offset, l.take_splice_anchor()), (150.0, 150.0));
}
#[test]
fn splices_tell_bound_cells_their_index_and_forget_gone_items() {
let mut l = list(100, 50.0, 400.0);
l.paced = true;
let mut binds = Vec::new();
l.update_window(&mut binds);
for &(slot, index) in &binds {
l.add_slot_cell(CellSlot::Item(slot), 100 + slot);
l.rendered(100 + slot, index);
}
l.splice(0, 0, 1);
binds.clear();
l.update_window(&mut binds);
let now: Vec<u32> = binds.iter().map(|b| b.1).collect();
assert_eq!(now, [1, 2, 3, 4, 5, 6, 7, 8, 0], "{binds:?}");
assert!(l.has_paced());
l.splice(3, 98, 0);
binds.clear();
l.update_window(&mut binds);
while l.take_paced(100, &mut binds) > 0 {}
assert!(binds.iter().all(|&(_, i)| i < 3), "{binds:?}");
}
#[test]
fn pins_follow_until_landed_measured_or_scrolled_away() {
let mut l = list(100, 50.0, 400.0);
l.pin(Some(PinTarget::End), 4600.0, true);
l.issue_scroll_to(4600.0);
l.measured(99, 90.0);
assert_eq!(l.follow_pin(0.0), Follow::To(4640.0));
l.issue_scroll_to(4640.0);
l.reported(3000.0, 2);
assert!(l.pinned(), "in flight");
l.reported(4640.0, 2);
l.measured(98, 60.0);
assert_eq!(l.follow_pin(0.0), Follow::By(10.0));
assert_eq!(l.offset, 4650.0);
assert!(l.pinned(), "rows in the viewport not measured yet");
l.reported(4000.0, 2);
assert!(!l.pinned());
l.pin(Some(PinTarget::End), 4650.0, false);
l.splice(0, 1, 0);
assert!(!l.pinned());
}
fn in_page(start: f32, offset: f32, max: f32) -> ListState {
let mut l = list(100, 50.0, 0.0);
l.set_parent(true);
l.set_outer(start, offset, 400.0, max, true);
l
}
fn bound(l: &ListState) -> Vec<u32> {
let mut bound: Vec<u32> = l.slots.iter().filter_map(|s| s.index).collect();
bound.sort_unstable();
bound
}
#[test]
fn in_a_page_the_window_is_the_viewport_over_the_list() {
let mut l = in_page(100.0, 0.0, 4700.0);
assert_eq!(l.offset, -100.0);
let mut binds = Vec::new();
l.update_window(&mut binds);
assert_eq!(bound(&l), (0..=14).collect::<Vec<_>>());
let mut l = in_page(1000.0, 0.0, 4700.0);
l.update_window(&mut binds);
assert!(bound(&l).is_empty());
let mut l = in_page(0.0, 5500.0, 6000.0);
l.update_window(&mut binds);
assert!(bound(&l).is_empty());
}
#[test]
fn in_a_page_load_more_fires_as_the_lists_end_nears() {
let mut l = list(20, 50.0, 0.0);
l.set_parent(true);
let mut binds = Vec::new();
for (offset, fires) in [(0.0, false), (1100.0, false), (1300.0, true)] {
l.set_outer(1000.0, offset, 400.0, 1600.0, true);
assert_eq!(l.update_window(&mut binds).end, fires, "at {offset}");
}
}
#[test]
fn in_a_page_only_changes_above_the_viewport_scroll_it() {
let mut l = in_page(100.0, 0.0, 4700.0);
assert_eq!(l.measured(0, 80.0), 0.0);
l.splice(0, 0, 3);
assert_eq!(l.take_splice_anchor(), 0.0);
let mut l = in_page(100.0, 1100.0, 4700.0);
assert_eq!(l.offset, 1000.0);
assert_eq!(l.measured(2, 80.0), 30.0);
assert_eq!(l.measured(25, 80.0), 0.0);
l.splice(0, 0, 2);
assert_eq!(l.take_splice_anchor(), 100.0);
}
#[test]
fn in_a_page_scroll_targets_are_clamped_by_the_page() {
let l = in_page(100.0, 0.0, 4700.0);
assert_eq!(l.offset_for_index(10, 0.0, 0.0), 500.0);
assert_eq!(l.offset_for_index(99, 0.0, 0.0), 4600.0);
assert_eq!(l.offset_for_index(0, 1.0, 0.0), -100.0);
assert_eq!(l.end_offset(), 4600.0);
assert_eq!(l.clamped(-500.0), -100.0);
}
#[test]
fn in_a_page_what_needs_a_scroll_view_of_its_own_is_off() {
let mut l = list(100, 50.0, 400.0);
l.set_inverted(true);
l.set_sticky(vec![0]);
l.set_parent(true);
assert!(!l.inverted && l.sticky_enabled());
assert_eq!(l.ignored, ignored::INVERTED);
l.set_follow_end(Some(10.0));
assert_eq!(l.follow_end, None);
assert_ne!(l.ignored & ignored::FOLLOW_END, 0);
}
#[test]
fn back_to_its_own_scroll_view_a_list_gets_back_what_parent_mode_set_aside() {
let mut l = list(100, 50.0, 400.0);
l.set_inverted(true);
l.set_follow_end(Some(10.0));
l.set_parent(true);
l.set_parent(false);
assert!(l.inverted);
assert_eq!(l.follow_end, Some(10.0));
}
#[test]
fn in_a_page_sticky_rows_travel_in_the_pages_offsets_to_the_lists_end() {
let mut l = in_page(100.0, 0.0, 4700.0);
l.set_sticky(vec![0, 30]);
l.set_sticky_offset(20.0);
assert_eq!(
l.sticky_range(0, 1, 50.0),
StickyRange {
cell: 1,
start: 80.0,
end: 100.0 + 1500.0 - 50.0 - 20.0,
offset: None,
}
);
let last = l.sticky_range(30, 2, 50.0);
assert_eq!(last.start, 100.0 + 1500.0 - 20.0);
assert_eq!(last.end, 100.0 + 5000.0 - 50.0 - 20.0);
l.set_outer(100.0, 1700.0, 400.0, 4700.0, true);
assert_eq!(l.active_sticky(), Some(30));
}
#[test]
fn in_a_page_a_pin_survives_the_list_moving_in_the_page() {
let mut l = in_page(100.0, 600.0, 4700.0);
l.pin(
Some(PinTarget::Index {
index: 10,
view_position: 0.0,
view_offset: 0.0,
}),
500.0,
false,
);
l.set_outer(140.0, 600.0, 400.0, 4740.0, true);
assert!(l.pinned());
l.set_outer(140.0, 900.0, 400.0, 4740.0, true);
assert!(!l.pinned());
}
#[test]
fn scroll_to_index() {
let mut l = list(100, 50.0, 400.0);
assert_eq!(l.offset_for_index(10, 0.0, 0.0), 500.0);
assert_eq!(l.offset_for_index(10, 0.5, 0.0), 500.0 - 175.0);
assert_eq!(l.offset_for_index(99, 0.0, 0.0), 5000.0 - 400.0);
l.set_inverted(true);
assert_eq!(l.offset_for_index(0, 0.0, 0.0), 4600.0);
}
fn bind_all(l: &mut ListState, binds: &mut Vec<(u32, u32)>) {
binds.clear();
l.update_window(binds);
for &(slot, index) in binds.iter() {
if l.slots[slot as usize].cell == u32::MAX {
l.add_slot_cell(CellSlot::Item(slot), 100 + slot);
}
l.rendered(100 + slot, index);
}
}
#[test]
fn items_take_back_the_free_cell_that_still_shows_them() {
let mut l = list(100, 50.0, 400.0);
let mut binds = Vec::new();
l.offset = 1000.0;
bind_all(&mut l, &mut binds);
let cells = |l: &ListState| -> Vec<(u32, u32)> {
let mut c: Vec<_> = l
.slots
.iter()
.filter_map(|s| s.index.map(|i| (i, s.cell)))
.collect();
c.sort_unstable();
c
};
let before = cells(&l);
l.viewport = 200.0;
bind_all(&mut l, &mut binds);
assert!(cells(&l).len() < before.len());
l.viewport = 400.0;
bind_all(&mut l, &mut binds);
assert_eq!(cells(&l), before, "each row is back in its own cell");
assert!(binds.is_empty(), "nothing to bind again: {binds:?}");
l.offset = 1200.0;
bind_all(&mut l, &mut binds);
assert!(!binds.is_empty());
}
#[test]
fn free_cells_follow_their_items_through_splices() {
let mut l = list(100, 50.0, 400.0);
let mut binds = Vec::new();
l.offset = 1000.0;
bind_all(&mut l, &mut binds);
let cell_of =
|l: &ListState, i: u32| l.slots.iter().find(|s| s.index == Some(i)).map(|s| s.cell);
let last = l.slots.iter().filter_map(|s| s.index).max().unwrap();
let own = cell_of(&l, last).unwrap();
l.viewport = 200.0;
bind_all(&mut l, &mut binds);
assert_eq!(cell_of(&l, last), None);
l.splice(0, 0, 2);
binds.clear();
l.update_window(&mut binds);
let slot = l.slots.iter().position(|s| s.cell == own).unwrap() as u32;
assert!(binds.contains(&(slot, last + 2)), "{binds:?}");
l.viewport = 400.0;
bind_all(&mut l, &mut binds);
assert_eq!(cell_of(&l, last + 2), Some(own));
assert!(!binds.iter().any(|&(s, _)| s == slot), "{binds:?}");
l.viewport = 200.0;
bind_all(&mut l, &mut binds);
assert_eq!(cell_of(&l, last + 2), None);
l.splice(last + 2, 1, 0);
let s = l.slots[slot as usize];
assert_eq!((s.rendered, s.requested), (None, None));
}
#[test]
fn kept_items_stay_rendered_out_of_the_window() {
let mut l = list(100, 50.0, 400.0);
l.set_kept(vec![2]);
l.offset = 3000.0;
let mut binds = Vec::new();
l.update_window(&mut binds);
let bound = |l: &ListState, i: u32| l.slots.iter().any(|s| s.index == Some(i));
assert!(bound(&l, 2), "{binds:?}");
assert!(!bound(&l, 3));
l.splice(0, 0, 1);
binds.clear();
l.update_window(&mut binds);
assert!(bound(&l, 3) && !bound(&l, 2), "{binds:?}");
l.set_kept(Vec::new());
binds.clear();
l.update_window(&mut binds);
assert!(!bound(&l, 3));
}
fn inverted_history(loads_at_start: bool) -> ListState {
let mut l = list(100, 50.0, 400.0);
l.set_inverted(true);
l.loads_at_start = loads_at_start;
l.anchor_end(0.0);
l.reported(400.0, 0);
l
}
fn lay_out(l: &mut ListState, measured: &[(u32, f32)]) {
let mut kept = 0.0;
for &(i, size) in measured {
kept += l.measured(i, size);
}
l.offset += kept;
let spliced = l.take_splice_anchor();
l.anchor_end(kept + spliced);
}
#[test]
fn follow_end_list_near_its_start_keeps_a_page_prepended_above() {
let mut l = list(12, 66.0, 449.0);
l.follow_end = Some(100.0);
lay_out(&mut l, &(0..12).map(|i| (i, 66.0)).collect::<Vec<_>>());
l.reported(30.0, 0);
lay_out(&mut l, &[]);
let before = l.to_content(l.item_at(0), 66.0) - l.offset;
l.splice(0, 0, 6);
lay_out(&mut l, &(0..6).map(|i| (i, 66.0)).collect::<Vec<_>>());
let end = l.content_len() - l.viewport;
assert!(
l.offset < end - 100.0,
"offset {} followed the end {end}",
l.offset
);
assert_eq!(l.to_content(l.item_at(6), 66.0) - l.offset, before);
}
fn on_screen(l: &ListState, i: u32) -> f32 {
l.to_content(l.item_at(i), 50.0) - l.offset
}
#[test]
fn inverted_page_and_row_above_viewport_measured_in_one_layout() {
let mut l = inverted_history(true);
let before = on_screen(&l, 84);
l.splice(100, 0, 10);
lay_out(&mut l, &[(93, 80.0)]);
assert_eq!(on_screen(&l, 84), before);
}
#[test]
fn inverted_page_and_row_above_viewport_in_separate_layouts() {
let mut l = inverted_history(true);
let before = on_screen(&l, 84);
l.splice(100, 0, 10);
lay_out(&mut l, &[]);
assert_eq!(on_screen(&l, 84), before);
lay_out(&mut l, &[(93, 80.0)]);
assert_eq!(on_screen(&l, 84), before);
}
#[test]
fn inverted_page_with_rows_below_and_above_viewport_in_one_layout() {
let mut l = inverted_history(true);
let before = on_screen(&l, 84);
l.splice(100, 0, 10);
lay_out(&mut l, &[(80, 80.0), (93, 80.0)]);
assert_eq!(on_screen(&l, 84), before);
}
#[test]
fn inverted_without_load_more_at_start_keeps_its_distance_from_the_end() {
let mut l = inverted_history(false);
let distance = l.content_len() - l.offset;
l.splice(100, 0, 10);
lay_out(&mut l, &[(93, 80.0), (80, 80.0)]);
assert_eq!(l.content_len() - l.offset, distance);
}
#[test]
fn inverted_at_its_start_follows_the_newest_row() {
let mut l = inverted_history(true);
l.reported(l.anchored_end, 0);
l.splice(100, 0, 10);
lay_out(&mut l, &[(0, 80.0), (8, 80.0)]);
assert_eq!(l.offset, l.content_len() - l.viewport);
}
#[test]
fn list_not_inverted_keeps_rows_when_rows_above_are_measured() {
let mut l = list(100, 50.0, 400.0);
l.reported(1000.0, 0);
let at = |l: &ListState| l.item_at(25) - l.offset;
let before = at(&l);
l.splice(100, 0, 10);
lay_out(&mut l, &[(15, 80.0), (30, 80.0)]);
assert_eq!(at(&l), before);
}
}
#[cfg(test)]
mod perf {
use std::time::Instant;
use super::*;
#[test]
#[ignore]
fn list_costs() {
let n = 100_000u32;
let mut l = ListState::new();
l.set_estimated(40.0);
l.viewport = 800.0;
let t = Instant::now();
for c in 1..=n {
l.set_count(c);
}
eprintln!("append 1-by-1 to {n}: {:?}", t.elapsed());
let t = Instant::now();
for c in 0..20_000u32 {
l.splice(l.count, 0, 1);
let _ = c;
}
eprintln!("splice-append 20k: {:?}", t.elapsed());
let mut binds = Vec::new();
l.update_window(&mut binds);
for (slot, i) in binds.drain(..) {
l.rendered(slot, i);
}
let t = Instant::now();
let frames = 20_000;
for f in 0..frames {
l.offset = (f as f32) * 7.0;
l.update_window(&mut binds);
for (slot, i) in binds.drain(..) {
l.rendered(slot, i);
l.measured(i, 44.0);
}
}
eprintln!("scroll frame avg: {:?}", t.elapsed() / frames);
}
}