Skip to main content

tvui/
viewer.rs

1//! The read-only text window body: lines scrolled by row under the frame scrollbar.
2
3use ratatui::buffer::Buffer;
4use ratatui::layout::Rect;
5
6use crate::desktop::MIN_SIZE;
7use crate::text_view::{column, draw_row};
8use crate::{Role, RowWindow, Theme, inner, render_scrollbar};
9
10/// Border cells around the content on each axis.
11const FRAME: usize = 2;
12
13/// The window size that shows all of `lines` whole inside the frame, at least the minimum
14/// window size.
15#[must_use]
16pub fn viewer_size<S: AsRef<str>>(lines: &[S]) -> (u16, u16) {
17    let widest = lines
18        .iter()
19        .map(|line| column(line.as_ref(), usize::MAX))
20        .max()
21        .unwrap_or(0);
22    let cells = |content: usize, least: u16| {
23        u16::try_from(content.saturating_add(FRAME))
24            .unwrap_or(u16::MAX)
25            .max(least)
26    };
27    (cells(widest, MIN_SIZE.0), cells(lines.len(), MIN_SIZE.1))
28}
29
30/// Draws `lines` and the scrollbar inside the frame of a window drawn in `area`, from the row
31/// `scroll` holds, which the draw keeps inside the last page.
32pub fn render_viewer<S: AsRef<str>>(
33    theme: &Theme,
34    lines: &[S],
35    area: Rect,
36    scroll: &RowWindow,
37    buf: &mut Buffer,
38) {
39    let body = inner(area).intersection(buf.area);
40    let view = usize::from(body.height);
41    let top = scroll.fit(lines.len(), view);
42    let style = theme.style(Role::Panel);
43    let shown = lines.iter().skip(top);
44    for (y, line) in (body.y..body.bottom()).zip(shown) {
45        draw_row(buf, body, y, line.as_ref(), 0, style);
46    }
47    render_scrollbar(theme, area, buf, (lines.len(), view, top));
48}
49
50#[cfg(test)]
51mod tests;