use crate::block::{Block, BorderStyle}; use crate::style::Line; /// A fixed-height panel that shows the last `max_height` lines of a log. /// Pure Block builder — no IO or interactive state. #[derive(Debug, Clone)] pub struct LogPanel { lines: Vec, max_height: usize, border: Option, title: Option, } impl LogPanel { pub fn new(max_height: usize) -> Self { LogPanel { lines: Vec::new(), max_height, border: None, title: None, } } /// Append a styled line to the log. Returns `Self` for chaining. pub fn push(mut self, line: Line) -> Self { self.lines.push(line); self } /// Append a styled line (mutable borrow version, for use in loops). pub fn push_mut(&mut self, line: Line) { self.lines.push(line); } /// Append a plain text line. pub fn plain(self, text: &str) -> Self { use crate::style::Span; self.push(vec![Span::plain(text)]) } pub fn border(self, b: BorderStyle) -> Self { Self { border: Some(b), ..self } } pub fn title(self, t: Line) -> Self { Self { title: Some(t), ..self } } /// The number of lines currently stored. pub fn len(&self) -> usize { self.lines.len() } pub fn is_empty(&self) -> bool { self.lines.is_empty() } /// Render the last `max_height` lines as a Block. pub fn to_block(&self) -> Block { let skip = self.lines.len().saturating_sub(self.max_height); let visible: Vec = self.lines[skip..].to_vec(); let content = Block::text(visible); match &self.border { None => content, Some(b) => Block::boxed(content, b.clone(), self.title.clone()), } } } #[cfg(test)] mod tests { use super::*; use crate::style::Span; fn plain_line(s: &str) -> Line { vec![Span::plain(s)] } #[test] fn shows_last_n_lines() { let panel = LogPanel::new(3) .push(plain_line("a")) .push(plain_line("b")) .push(plain_line("c")) .push(plain_line("d")) .push(plain_line("e")); let block = panel.to_block(); let lines = block.render(10); assert_eq!(lines.len(), 3); assert!(lines[0].contains("c")); assert!(lines[1].contains("d")); assert!(lines[2].contains("e")); } #[test] fn fewer_than_max_shows_all() { let panel = LogPanel::new(10) .push(plain_line("x")) .push(plain_line("y")); let block = panel.to_block(); let lines = block.render(10); assert_eq!(lines.len(), 2); } #[test] fn empty_panel() { let panel = LogPanel::new(5); let block = panel.to_block(); let lines = block.render(10); assert_eq!(lines.len(), 0); } #[test] fn with_border_adds_two_rows() { let panel = LogPanel::new(3) .push(plain_line("hello")) .border(BorderStyle::Single); let block = panel.to_block(); let lines = block.render(20); assert_eq!(lines.len(), 3); // top border + 1 content + bottom border } #[test] fn push_mut_works() { let mut panel = LogPanel::new(5); panel.push_mut(plain_line("a")); panel.push_mut(plain_line("b")); assert_eq!(panel.len(), 2); } #[test] fn plain_convenience() { let panel = LogPanel::new(5).plain("hello world"); let block = panel.to_block(); let lines = block.render(20); assert!(lines[0].contains("hello world")); } }