use std::slice::Iter;
use crate::{
cell::{Cell, Cells},
utils::formatting::content_split::measure_text_width,
};
#[derive(Clone, Debug, Default)]
pub struct Row {
pub(crate) index: Option<usize>,
pub(crate) cells: Vec<Cell>,
pub(crate) max_height: Option<usize>,
}
impl Row {
pub fn new() -> Self {
Self::default()
}
pub fn add_cell(&mut self, cell: Cell) -> &mut Self {
self.cells.push(cell);
self
}
pub fn max_height(&mut self, lines: usize) -> &mut Self {
self.max_height = Some(lines);
self
}
pub(crate) fn max_content_widths(&self) -> Vec<usize> {
self.cells
.iter()
.map(|cell| {
cell.content
.iter()
.map(|string| measure_text_width(string))
.max()
.unwrap_or(0)
})
.collect()
}
pub fn cell_count(&self) -> usize {
self.cells.len()
}
pub fn cell_iter(&self) -> Iter<Cell> {
self.cells.iter()
}
}
impl<T: Into<Cells>> From<T> for Row {
fn from(cells: T) -> Self {
Self {
index: None,
cells: cells.into().0,
max_height: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_correct_max_content_width() {
let row = Row::from(vec![
"",
"four",
"fivef",
"sixsix",
"11 but with\na newline",
]);
let max_content_widths = row.max_content_widths();
assert_eq!(max_content_widths, vec![0, 4, 5, 6, 11]);
}
#[test]
fn test_some_functions() {
let cells = ["one", "two", "three"];
let mut row = Row::new();
for cell in cells.iter() {
row.add_cell(Cell::new(cell));
}
assert_eq!(row.cell_count(), cells.len());
let mut cell_content_iter = cells.iter();
for cell in row.cell_iter() {
assert_eq!(
cell.content(),
cell_content_iter.next().unwrap().to_string()
);
}
}
}