pub const GAP: f32 = 6.0;
pub const GUESS: f32 = 1.42;
pub const BEHIND: usize = 1;
pub const AHEAD: usize = 2;
pub fn column(w: f32, h: f32) -> f32 {
w.min(h * 0.75).max(1.0)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pos {
pub top: usize,
pub offset: f32,
}
pub fn scroll(pos: Pos, dy: f32, n: usize, view: f32, height: impl Fn(usize) -> f32) -> (Pos, bool) {
if n == 0 {
return (Pos { top: 0, offset: 0.0 }, true);
}
let mut top = pos.top.min(n - 1);
let mut offset = pos.offset + dy;
while offset < 0.0 && top > 0 {
top -= 1;
offset += height(top) + GAP;
}
if offset < 0.0 {
return (Pos { top: 0, offset: 0.0 }, true);
}
while top + 1 < n && offset >= height(top) + GAP {
offset -= height(top) + GAP;
top += 1;
}
let end = end(n, view, &height);
let past = (top, offset) > (end.top, end.offset);
if past { (end, dy > 0.0) } else { (Pos { top, offset }, false) }
}
pub fn end(n: usize, view: f32, height: impl Fn(usize) -> f32) -> Pos {
let mut top = n.saturating_sub(1);
let mut above = (view - height(top)).max(0.0);
let mut offset = (height(top) - view).max(0.0);
while above > 0.0 && top > 0 {
let h = height(top - 1) + GAP;
if h >= above {
offset = h - above;
above = 0.0;
} else {
above -= h;
}
top -= 1;
}
if above > 0.0 { Pos { top: 0, offset: 0.0 } } else { Pos { top, offset } }
}
pub fn visible(pos: Pos, n: usize, view: f32, height: impl Fn(usize) -> f32) -> Vec<(usize, f32, f32)> {
let mut out = Vec::new();
let mut y = -pos.offset;
let mut k = pos.top;
while k < n && y < view {
let h = height(k);
out.push((k, y, h));
y += h + GAP;
k += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn h(k: usize) -> f32 {
[100.0, 200.0, 50.0][k % 3]
}
#[test]
fn scrolling_crosses_pages_and_stops_at_both_ends() {
let at = |top, offset| Pos { top, offset };
assert_eq!(scroll(at(0, 0.0), 130.0, 6, 80.0, h), (at(1, 130.0 - 100.0 - GAP), false));
assert_eq!(scroll(at(1, 10.0), -20.0, 6, 80.0, h), (at(0, 100.0 + GAP - 10.0), false));
assert_eq!(scroll(at(0, 5.0), -50.0, 6, 80.0, h), (at(0, 0.0), true));
let (last, stopped) = scroll(at(0, 0.0), 10_000.0, 6, 80.0, h);
assert!(stopped);
let shown = visible(last, 6, 80.0, h);
let (k, y, hh) = *shown.last().unwrap();
assert_eq!(k, 5);
assert!((y + hh - 80.0).abs() < 0.01, "{shown:?}");
assert!(!scroll(last, -1.0, 6, 80.0, h).1);
}
#[test]
fn a_short_book_does_not_scroll() {
let small = |_| 20.0;
assert_eq!(end(2, 500.0, small), Pos { top: 0, offset: 0.0 });
assert_eq!(scroll(Pos { top: 0, offset: 0.0 }, 30.0, 2, 500.0, small).0, Pos { top: 0, offset: 0.0 });
}
#[test]
fn the_pages_on_screen_follow_each_other_with_a_gap() {
let v = visible(Pos { top: 1, offset: 150.0 }, 6, 200.0, h);
assert_eq!(v[0], (1, -150.0, 200.0));
assert_eq!(v[1], (2, 50.0 + GAP, 50.0));
assert_eq!(v[2].0, 3);
assert!(v.iter().all(|(_, y, _)| *y < 200.0));
}
#[test]
fn the_column_is_at_most_three_quarters_of_the_height() {
assert_eq!(column(1920.0, 1000.0), 750.0);
assert_eq!(column(400.0, 1000.0), 400.0);
}
}