Files
hx/crates/hx-tui/src/scroll.rs
T
hermes f0a0111343
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
Scrolling: mouse wheel per region, page/line/top/bottom keys, pinned view while streaming
2026-10-02 14:31:55 +00:00

97 lines
2.9 KiB
Rust

//! Scroll position of a text view. `top: None` follows the bottom (new text stays in view);
//! `Some(n)` pins line `n` at the top, so streaming text below doesn't move what you are reading.
#[derive(Default, Debug, Clone, PartialEq)]
pub struct Scroll {
top: Option<u16>,
/// last drawn size, so key/mouse handlers can page without knowing the layout
total: u16,
height: u16,
}
impl Scroll {
fn max(&self) -> u16 {
self.total.saturating_sub(self.height)
}
fn cur(&self) -> u16 {
self.top.unwrap_or(self.max()).min(self.max())
}
/// Call while drawing with the content's line count and the view height; returns the first
/// line to show. Reaching the bottom goes back to following.
pub fn resolve(&mut self, total: u16, height: u16) -> u16 {
self.total = total;
self.height = height;
if self.top.is_some_and(|t| t >= self.max()) {
self.top = None;
}
self.cur()
}
pub fn up(&mut self, n: u16) {
self.top = Some(self.cur().saturating_sub(n));
}
pub fn down(&mut self, n: u16) {
self.top = Some(self.cur().saturating_add(n));
if self.top.is_some_and(|t| t >= self.max()) {
self.top = None;
}
}
pub fn half_page(&self) -> u16 {
(self.height / 2).max(1)
}
pub fn page(&self) -> u16 {
self.height.saturating_sub(1).max(1)
}
pub fn start(&mut self) {
self.top = Some(0);
}
pub fn end(&mut self) {
self.top = None;
}
/// Lines below the view (0 when following).
pub fn behind(&self) -> u16 {
self.max() - self.cur()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn follows_bottom_until_scrolled_and_pins_while_content_grows() {
let mut s = Scroll::default();
assert_eq!(s.resolve(100, 20), 80);
s.up(10);
assert_eq!((s.resolve(100, 20), s.behind()), (70, 10));
// 30 more lines stream in: the pinned view stays, the gap grows
assert_eq!((s.resolve(130, 20), s.behind()), (70, 40));
// scrolling back down to the end resumes following
s.down(1000);
assert_eq!((s.resolve(130, 20), s.behind()), (110, 0));
assert_eq!(s.resolve(140, 20), 120);
}
#[test]
fn paging_clamping_start_end() {
let mut s = Scroll::default();
s.resolve(50, 10);
assert_eq!((s.half_page(), s.page()), (5, 9));
s.up(s.page());
assert_eq!(s.resolve(50, 10), 31);
s.start();
assert_eq!(s.resolve(50, 10), 0);
s.up(5);
assert_eq!(s.resolve(50, 10), 0, "no underflow");
s.end();
assert_eq!(s.resolve(50, 10), 40);
// content shorter than the view
let mut t = Scroll::default();
t.up(5);
assert_eq!((t.resolve(3, 10), t.behind()), (0, 0));
t.down(5);
assert_eq!(t.resolve(3, 10), 0);
}
}