use crate::primitives::termtui::attrs::Attrs;
use ratatui::buffer::Cell as RatatuiCell;
use unicode_width::UnicodeWidthChar;
#[derive(Clone, Debug, Default)]
pub struct Cell {
text: String,
attrs: Attrs,
}
impl Cell {
pub fn new() -> Self {
Self {
text: " ".to_string(),
attrs: Attrs::default(),
}
}
pub fn with_attrs(attrs: Attrs) -> Self {
Self {
text: " ".to_string(),
attrs,
}
}
pub fn text(&self) -> &str {
&self.text
}
pub fn set_text(&mut self, text: impl Into<String>) {
self.text = text.into();
}
pub fn attrs(&self) -> &Attrs {
&self.attrs
}
pub fn attrs_mut(&mut self) -> &mut Attrs {
&mut self.attrs
}
pub fn set_attrs(&mut self, attrs: Attrs) {
self.attrs = attrs;
}
pub fn width(&self) -> usize {
self.text
.chars()
.next()
.and_then(|c| c.width())
.unwrap_or(1)
}
pub fn is_wide_continuation(&self) -> bool {
self.text.is_empty()
}
pub fn set_wide_continuation(&mut self) {
self.text.clear();
}
pub fn clear(&mut self) {
self.text = " ".to_string();
self.attrs = Attrs::default();
}
pub fn clear_keep_attrs(&mut self) {
self.text = " ".to_string();
}
pub fn to_ratatui(&self) -> RatatuiCell {
let mut cell = RatatuiCell::default();
let ch = self.text.chars().next().unwrap_or(' ');
cell.set_char(ch);
cell.set_style(self.attrs.to_ratatui());
cell
}
}
impl PartialEq for Cell {
fn eq(&self, other: &Self) -> bool {
self.text == other.text && self.attrs == other.attrs
}
}
impl Eq for Cell {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cell_new() {
let cell = Cell::new();
assert_eq!(cell.text(), " ");
assert_eq!(cell.width(), 1);
}
#[test]
fn test_cell_set_text() {
let mut cell = Cell::new();
cell.set_text("A");
assert_eq!(cell.text(), "A");
}
#[test]
fn test_cell_wide_char() {
let mut cell = Cell::new();
cell.set_text("你");
assert_eq!(cell.width(), 2);
}
#[test]
fn test_cell_clear() {
let mut cell = Cell::new();
cell.set_text("X");
cell.attrs_mut().set_bold(true);
cell.clear();
assert_eq!(cell.text(), " ");
assert!(!cell.attrs().bold());
}
#[test]
fn test_cell_to_ratatui() {
let mut cell = Cell::new();
cell.set_text("A");
cell.attrs_mut().set_bold(true);
let ratatui_cell = cell.to_ratatui();
assert_eq!(ratatui_cell.symbol(), "A");
}
}