use crossterm::{cursor, execute, terminal};
use std::io::{self, stdout, Write};
pub struct Renderer {
last_render: String,
}
impl Renderer {
pub fn new() -> Self {
Self {
last_render: String::new(),
}
}
pub fn render(&mut self, content: &str) -> io::Result<()> {
if content == self.last_render {
return Ok(());
}
let mut stdout = stdout();
execute!(
stdout,
cursor::MoveTo(0, 0),
terminal::Clear(terminal::ClearType::All)
)?;
write!(stdout, "{}", content)?;
stdout.flush()?;
self.last_render = content.to_string();
Ok(())
}
pub fn clear(&mut self) -> io::Result<()> {
let mut stdout = stdout();
execute!(stdout, terminal::Clear(terminal::ClearType::All))?;
self.last_render.clear();
Ok(())
}
#[must_use]
pub fn size() -> (u16, u16) {
terminal::size().unwrap_or((80, 24))
}
}
impl Default for Renderer {
fn default() -> Self {
Self::new()
}
}