arkham/src/ui/cell.rs

94 lines
2.2 KiB
Rust

use crossterm::queue;
use crossterm::style::{
Attribute, Attributes, SetAttributes, SetBackgroundColor, SetForegroundColor,
};
use crossterm::style::{Color, Print};
use std::io::Write;
use crate::Result;
#[derive(Clone, Debug, Copy, PartialEq)]
pub struct Cell {
empty: bool,
fg: Color,
bg: Color,
content: char,
attributes: Attributes,
}
impl Default for Cell {
fn default() -> Self {
Self {
empty: true,
fg: Color::Reset,
bg: Color::Reset,
content: ' ',
attributes: Attributes::default(),
}
}
}
impl Cell {
pub fn new() -> Self {
Self::default()
}
pub fn content(&mut self, v: char) -> &mut Cell {
self.empty = false;
self.content = v;
self
}
pub fn fg(&mut self, color: Color) -> &mut Cell {
self.fg = color;
self
}
pub fn bg(&mut self, color: Color) -> &mut Cell {
self.bg = color;
self
}
pub fn bold(&mut self, v: bool) -> &mut Cell {
if v {
self.attributes.set(Attribute::Bold);
} else {
self.attributes.unset(Attribute::Bold);
}
self
}
pub fn render(&self, output: &mut impl Write) -> Result<()> {
if !self.empty {
queue!(output, SetForegroundColor(self.fg))?;
queue!(output, SetBackgroundColor(self.bg))?;
queue!(output, SetAttributes(self.attributes))?;
queue!(output, Print(&self.content))?;
}
Ok(())
}
pub fn raw(&self) -> Vec<u8> {
let mut output: Vec<u8> = vec![];
self.render(&mut output).expect("Render error");
output
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cell_render() {
let mut cell = Cell::default();
cell.fg(Color::Red);
cell.bg(Color::White);
cell.content = 'T';
cell.bold(true);
let mut output: Vec<u8> = vec![];
cell.render(&mut output).expect("Render error");
let out_str = String::from_utf8(output).expect("Couldnt unwrap to utf8");
assert_eq!(out_str, "\u{1b}[38;5;9m\u{1b}[48;5;15m\u{1b}[1mT");
}
}