use crate::{Align, BlockStyle, GridStyle, Sides, VerticalAlign, View};
static ABSENT: View = View::empty();
pub(super) fn columns(rows: &[Vec<View>]) -> usize {
debug_assert!(
rows.windows(2).all(|pair| pair[0].len() == pair[1].len()),
"a grid is a rectangle: every row holds the same number of cells"
);
rows.iter().map(Vec::len).max().unwrap_or(0)
}
pub(super) fn cell(rows: &[Vec<View>], row: usize, column: usize) -> &View {
rows[row].get(column).unwrap_or(&ABSENT)
}
pub(super) fn cell_padding(style: &GridStyle, cell: &View) -> Sides {
match box_style(cell) {
Some(block) if block.get_padding() != Sides::default() => Sides::default(),
_ => style.get_cell_padding(),
}
}
pub(super) fn cell_alignment(cell: &View) -> (Align, VerticalAlign) {
match box_style(cell) {
Some(block) => (block.get_align(), block.get_vertical_align()),
None => (Align::default(), VerticalAlign::default()),
}
}
const fn box_style(cell: &View) -> Option<&BlockStyle> {
match cell {
View::Block(block, _, _) | View::AnchorBlock(_, block, _, _) => Some(block),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Length, TextStyle};
fn text(content: &str) -> View {
View::text(content, TextStyle::new())
}
#[test]
fn every_cell_of_a_rectangle_is_the_one_that_was_put_there() {
let rows = vec![vec![text("a"), text("b")], vec![text("c"), text("d")]];
assert_eq!(columns(&rows), 2);
assert_eq!(cell(&rows, 1, 0), &text("c"));
assert_eq!(cell(&rows, 1, 1), &text("d"));
}
#[test]
#[should_panic(expected = "a grid is a rectangle")]
fn rejects_a_ragged_grid() {
let _ = columns(&[vec![text("a"), text("b")], vec![text("c")]]);
}
#[test]
fn a_cell_a_ragged_grid_does_not_hold_is_empty() {
let rows = vec![vec![text("a"), text("b")], vec![text("c")]];
assert_eq!(cell(&rows, 1, 1), &View::empty());
}
#[test]
fn a_cell_that_states_padding_replaces_the_grids() {
let style = GridStyle::new().cell_padding((0, 1));
let stated = View::block(BlockStyle::new().padding((1, 2)), text("a"));
assert_eq!(cell_padding(&style, &text("a")), Sides::from((0, 1)));
assert_eq!(
cell_padding(&style, &View::block(BlockStyle::new(), text("a"))),
Sides::from((0, 1)),
"a box that states none takes the grid's"
);
assert_eq!(
cell_padding(&style, &stated),
Sides::default(),
"and one that states its own keeps only that"
);
}
#[test]
fn a_cell_that_is_not_a_box_states_no_alignment() {
let aligned = View::block(
BlockStyle::new()
.align(Align::Right)
.vertical_align(VerticalAlign::Bottom),
text("a"),
);
assert_eq!(
cell_alignment(&text("a")),
(Align::Left, VerticalAlign::Top)
);
assert_eq!(
cell_alignment(&aligned),
(Align::Right, VerticalAlign::Bottom)
);
}
#[test]
fn a_stated_column_length_is_read_by_index() {
let style = GridStyle::new().columns([Some(Length::fill(2))]);
assert_eq!(style.get_column(0), Some(Length::fill(2)));
assert_eq!(style.get_column(1), None);
}
}