//! Scrollable line widget. //! //! `ScrollView` renders scrollable line collections and draws a scrollbar when //! content exceeds the visible area. It is the widget-level bridge between //! viewport math and actual line rendering. use crate::{Scrollbar, ScrollbarStyle, View}; use rustik_tui_core as tui_core; use tui_core::{Buffer, Constraint, Line, Rect, Size, Widget}; /// Scrollable line metrics for a rendered area. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct ScrollMetrics { /// Number of content rows. pub content_rows: usize, /// Number of visible rows. pub visible_rows: usize, /// Visible view after offset clamping. pub view: View, } impl ScrollMetrics { /// Returns the largest valid scroll offset for the rendered view. pub fn max_offset(self) -> usize { self.view.max_offset() } } impl Default for ScrollMetrics { fn default() -> Self { Self { content_rows: 0, visible_rows: 0, view: View::new(0, 0, 0), } } } /// A scrollable collection of lines. #[derive(Debug, Clone)] pub struct ScrollView { lines: Vec, offset: usize, sticky: Vec, scrollbar: ScrollbarStyle, } /// A scrollable collection that renders rows on demand. pub struct VirtualScrollView { /// Number of rows in the full content. content_rows: usize, /// First visible content row before clamping. offset: usize, /// Optional view used only for scrollbar geometry. scrollbar_view: Option, /// Sticky rows pinned at the top of the view. sticky: Vec, /// Scrollbar style. scrollbar: ScrollbarStyle, /// Width-sensitive row producer. line: F, } /// Layout rectangles for a scroll-view render pass. #[derive(Clone, Copy, Debug)] pub struct ScrollLayout { /// Text area excluding the scrollbar. pub text: Rect, /// Optional scrollbar area. pub scrollbar: Option, /// Sticky rows that fit in the text area. pub sticky_rows: usize, /// Body area for scrolled content rows. pub body: Rect, } /// Layout information for one scroll-view render pass. #[derive(Clone, Copy, Debug)] struct ScrollFrame { /// Area rectangles for the render pass. layout: ScrollLayout, /// Clamped view for the scrolled body. view: View, } impl ScrollView { /// Returns the body width inside the reserved scrollbar column. /// /// Callers that pre-build content lines should size them to this width so /// they exactly fit the body next to the scrollbar. pub const fn body_cols(area: Rect) -> usize { if area.cols > 2 { area.cols - 1 } else { area.cols } } /// Creates a scroll view from prebuilt render lines. pub fn from_lines(lines: impl IntoIterator) -> Self { Self { lines: lines.into_iter().collect(), offset: 0, sticky: Vec::new(), scrollbar: ScrollbarStyle::default(), } } /// Builds a scroll view for an area from a width-sensitive line producer. /// /// The producer is called once with the body width that ScrollView will use /// (see [`body_cols`](Self::body_cols)). pub fn new(area: Rect, offset: usize, mut lines: impl FnMut(usize) -> Vec) -> Self { Self { lines: lines(Self::body_cols(area)), offset, sticky: Vec::new(), scrollbar: ScrollbarStyle::default(), } } /// Creates a scroll view that renders only visible rows. pub fn virtualized(content_rows: usize, offset: usize, line: F) -> VirtualScrollView where F: FnMut(usize, usize) -> Line, { VirtualScrollView::new(content_rows, offset, line) } /// Sets the first visible row. pub const fn offset(mut self, offset: usize) -> Self { self.offset = offset; self } /// Sets sticky rows pinned at the top of the view above the scrolled body. pub fn sticky(mut self, lines: impl IntoIterator) -> Self { self.sticky = lines.into_iter().collect(); self } /// Sets the vertical scrollbar style. pub fn scrollbar(mut self, style: ScrollbarStyle) -> Self { self.scrollbar = style; self } /// Returns metrics for a rendered area. pub fn metrics(&self, area: Rect) -> ScrollMetrics { let frame = scroll_frame(area, self.offset, self.lines.len(), self.sticky.len()); ScrollMetrics { content_rows: self.lines.len(), visible_rows: frame.layout.body.rows, view: frame.view, } } } impl VirtualScrollView where F: FnMut(usize, usize) -> Line, { /// Creates a virtual scroll view from a row count and row producer. pub fn new(content_rows: usize, offset: usize, line: F) -> Self { Self { content_rows, offset, scrollbar_view: None, sticky: Vec::new(), scrollbar: ScrollbarStyle::default(), line, } } /// Sets sticky rows pinned at the top of the view above the scrolled body. pub fn sticky(mut self, lines: impl IntoIterator) -> Self { self.sticky = lines.into_iter().collect(); self } /// Sets the vertical scrollbar style. pub fn scrollbar(mut self, style: ScrollbarStyle) -> Self { self.scrollbar = style; self } /// Sets the view used to derive scrollbar position and size. pub const fn scrollbar_view(mut self, view: View) -> Self { self.scrollbar_view = Some(view); self } /// Returns metrics for a rendered area. pub fn metrics(&self, area: Rect) -> ScrollMetrics { let frame = scroll_frame(area, self.offset, self.content_rows, self.sticky.len()); ScrollMetrics { content_rows: self.content_rows, visible_rows: frame.layout.body.rows, view: frame.view, } } } impl std::fmt::Debug for VirtualScrollView { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("VirtualScrollView") .field("content_rows", &self.content_rows) .field("offset", &self.offset) .field("scrollbar_view", &self.scrollbar_view) .field("sticky", &self.sticky) .field("scrollbar", &self.scrollbar) .finish_non_exhaustive() } } impl Widget for ScrollView { fn size(&self, parent: Constraint) -> Size { Size::new(parent.max.cols, parent.max.rows).constrain(parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { if area.is_empty() { return; } let frame = scroll_frame(area, self.offset, self.lines.len(), self.sticky.len()); render_sticky(&self.sticky, frame.layout, buf); frame.view.render_lines(&self.lines, frame.layout.body, buf); if let Some(area) = frame.layout.scrollbar { Scrollbar::new(frame.view) .style(self.scrollbar.clone()) .render(area, buf); } } } impl Widget for VirtualScrollView where F: FnMut(usize, usize) -> Line + Send, { fn size(&self, parent: Constraint) -> Size { Size::new(parent.max.cols, self.content_rows).constrain(parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { if area.is_empty() { return; } let frame = scroll_frame(area, self.offset, self.content_rows, self.sticky.len()); render_sticky(&self.sticky, frame.layout, buf); let lines = frame .view .range() .map(|row| (self.line)(row, frame.layout.body.cols)); Line::renders(lines, frame.layout.body, buf); if let Some(area) = frame.layout.scrollbar { Scrollbar::new(self.scrollbar_view.unwrap_or(frame.view)) .style(self.scrollbar.clone()) .render(area, buf); } } } /// Renders sticky lines into the top of a scroll layout's text area. fn render_sticky(sticky: &[Line], layout: ScrollLayout, buf: &mut Buffer) { if layout.sticky_rows == 0 { return; } let sticky_area = Rect::new( layout.text.x, layout.text.y, layout.text.cols, layout.sticky_rows, ); Line::renders( sticky.iter().take(layout.sticky_rows).cloned(), sticky_area, buf, ); } /// Returns the area rectangles for a scroll view with `sticky_rows` pinned. /// /// Splits `area` into a text column (excluding the rightmost scrollbar column /// when there is room for one), then divides the text area into a sticky /// header band of `sticky_rows` rows and a body for scrolled content. pub fn scroll_layout(area: Rect, sticky_rows: usize) -> ScrollLayout { let (text, scrollbar) = if area.cols > 2 { let text = Rect::new(area.x, area.y, area.cols - 1, area.rows); let scrollbar = Some(Rect::new(area.right() - 1, area.y, 1, area.rows)); (text, scrollbar) } else { (area, None) }; let sticky_rows = sticky_rows.min(text.rows); let body = Rect::new( text.x, text.y + sticky_rows, text.cols, text.rows.saturating_sub(sticky_rows), ); ScrollLayout { text, scrollbar, sticky_rows, body, } } /// Returns layout rectangles and view state for one scroll-view render pass. fn scroll_frame(area: Rect, offset: usize, content_rows: usize, sticky_rows: usize) -> ScrollFrame { let layout = scroll_layout(area, sticky_rows); let view = View::new(offset, content_rows, layout.body.rows); ScrollFrame { layout, view } } #[cfg(test)] mod tests { use super::*; use rustik_tui_core::{Buffer, Cell, Color, Style}; #[test] fn scrollbar_column_shows_track_only_when_content_fits() { let mut view = ScrollView::from_lines([Line::new("hello")]); let mut buffer = Buffer::empty(Rect::new(0, 0, 7, 2)); view.render(buffer.area(), &mut buffer); // 6-col body + 1-col scrollbar; non-scrollable view paints track only. assert_eq!(buffer.lines(), vec!["hello │", " │"]); } #[test] fn sticky_rows_pin_to_top_above_scrolled_body() { let lines = (0..6) .map(|i| Line::new(format!("row{i}"))) .collect::>(); let mut view = ScrollView::from_lines(lines) .offset(2) .sticky([Line::new("HEAD")]); let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 3)); view.render(buffer.area(), &mut buffer); assert_eq!(buffer.lines(), vec!["HEAD│", "row2┃", "row3│"]); } #[test] fn scroll_view_builds_lines_at_body_width() { let style = ScrollbarStyle::new( Cell::new('|', Style::new(Color::Unset)), Cell::new('#', Style::new(Color::Unset)), ); let area = Rect::new(0, 0, 4, 2); let mut view = ScrollView::new(area, 1, |cols| { (0..3) .map(|row| Line::new(format!("{row}:{cols}"))) .collect() }) .scrollbar(style); let metrics = view.metrics(area); let mut buffer = Buffer::empty(area); view.render(buffer.area(), &mut buffer); assert_eq!(ScrollView::body_cols(area), 3); assert_eq!(metrics.content_rows, 3); assert_eq!(metrics.visible_rows, 2); assert_eq!(buffer.lines(), vec!["1:3|", "2:3#"]); } #[test] fn virtual_scroll_view_renders_only_visible_rows() { let mut rendered = Vec::new(); let mut view = ScrollView::virtualized(10, 4, |row, cols| { rendered.push(row); Line::new(format!("{row}:{cols}")) }); let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 3)); view.render(buffer.area(), &mut buffer); assert_eq!(rendered, vec![4, 5, 6]); assert_eq!(buffer.lines(), vec!["4:4 │", "5:4 ┃", "6:4 │"]); } #[test] fn virtual_scroll_view_keeps_sticky_rows_out_of_source() { let mut rendered = Vec::new(); let mut view = ScrollView::virtualized(10, 4, |row, cols| { rendered.push(row); Line::new(format!("{row}:{cols}")) }) .sticky([Line::new("HEAD")]); let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 3)); view.render(buffer.area(), &mut buffer); assert_eq!(rendered, vec![4, 5]); assert_eq!(buffer.lines(), vec!["HEAD│", "4:4 ┃", "5:4 │"]); } #[test] fn virtual_scroll_view_can_use_logical_scrollbar_view() { let style = ScrollbarStyle::new( Cell::new('.', Style::new(Color::Unset)), Cell::new('#', Style::new(Color::Unset)), ); let mut view = ScrollView::virtualized(20, 7, |row, _| Line::new(row.to_string())) .sticky([Line::blank(), Line::blank(), Line::blank()]) .scrollbar_view(View::new(4, 20, 10)) .scrollbar(style); let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 10)); view.render(buffer.area(), &mut buffer); let thumb_rows = buffer .lines() .iter() .filter(|line| line.ends_with('#')) .count(); assert_eq!(thumb_rows, 5); } }