use crate::layout::group::{BASELINE_TOL, LINE_SPLIT_GAP};
use crate::layout::{Block, Page, Word};
pub const CORE_ASCENT: f32 = 0.7;
pub const CORE_DESCENT: f32 = 0.2;
pub const ROW_OVERLAP: f32 = 0.1;
pub const MERGE_GAP: f32 = 1.5;
pub const CONT_GAP: f32 = 0.5;
pub const CONT_ALIGN: f32 = 0.1;
pub const MIN_MULTI_ROWS: usize = 3;
pub const MIN_GUTTER: f32 = 0.3;
pub const ALIGN_EM: f32 = 0.05;
pub const ALIGN_MIN_PT: f32 = 0.5;
pub const MIN_BOTH: usize = 3;
pub const GAPPED_RATIO: f32 = 1.2;
pub const MIN_STEP: f32 = 0.5;
pub const CELL_CHAIN: f32 = 1.15;
const MAX_LINES: usize = 4000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Align {
Left,
Right,
Center,
}
pub type Cell = Vec<Vec<Word>>;
#[derive(Clone, Debug, PartialEq)]
pub enum Body {
Grid {
align: Vec<Align>,
rows: Vec<Vec<Cell>>,
},
Layout { rows: Vec<Vec<Word>> },
}
#[derive(Clone, Debug, PartialEq)]
pub struct Table {
pub blocks: Vec<usize>,
pub body: Body,
}
pub fn detect(page: &Page, eligible: impl Fn(usize) -> bool) -> Vec<Table> {
let mut out = Vec::new();
for r in 0..page.regions.len().max(1) {
let ids: Vec<usize> = (0..page.blocks.len())
.filter(|&i| page.blocks[i].region == r && eligible(i))
.collect();
for blocks in candidates(&page.blocks, &ids) {
let lines: Vec<(usize, &crate::layout::Line)> = blocks
.iter()
.flat_map(|&b| page.blocks[b].lines.iter().map(move |l| (b, l)))
.collect();
if let Some(body) = analyze(&lines) {
out.push(Table { blocks, body });
}
}
}
out.sort_by_key(|t| t.blocks.first().copied());
out
}
#[derive(Clone, Copy)]
struct LineBox {
block: usize,
top: f32,
bottom: f32,
left: f32,
right: f32,
size: f32,
}
fn core(l: &crate::layout::Line) -> (f32, f32) {
(
l.baseline - CORE_ASCENT * l.size,
l.baseline + CORE_DESCENT * l.size,
)
}
fn v_overlap(a: (f32, f32), b: (f32, f32)) -> f32 {
a.1.min(b.1) - a.0.max(b.0)
}
fn find(parent: &mut [usize], mut i: usize) -> usize {
while parent[i] != i {
parent[i] = parent[parent[i]];
i = parent[i];
}
i
}
fn candidates(blocks: &[Block], ids: &[usize]) -> Vec<Vec<usize>> {
let boxes: Vec<LineBox> = ids
.iter()
.flat_map(|&b| {
blocks[b].lines.iter().map(move |l| {
let (top, bottom) = core(l);
LineBox {
block: b,
top,
bottom,
left: l.bbox.left,
right: l.bbox.right,
size: l.size,
}
})
})
.collect();
if boxes.len() > MAX_LINES {
return Vec::new();
}
let pos = |b: usize| ids.iter().position(|&x| x == b).unwrap_or(0);
let mut parent: Vec<usize> = (0..ids.len()).collect();
for (i, a) in boxes.iter().enumerate() {
for b in &boxes[i + 1..] {
if a.block == b.block {
continue;
}
let min = a.size.min(b.size);
let disjoint = a.right <= b.left || b.right <= a.left;
if disjoint && v_overlap((a.top, a.bottom), (b.top, b.bottom)) > ROW_OVERLAP * min {
let (x, y) = (
find(&mut parent, pos(a.block)),
find(&mut parent, pos(b.block)),
);
parent[x.max(y)] = x.min(y);
}
}
}
struct Group {
blocks: Vec<usize>,
top: f32,
bottom: f32,
left: f32,
right: f32,
size: f32,
}
let mut groups: Vec<Group> = Vec::new();
for root in 0..ids.len() {
let members: Vec<usize> = (0..ids.len())
.filter(|&k| find(&mut parent, k) == root)
.map(|k| ids[k])
.collect();
if members.len() < 2 {
continue;
}
let bx = boxes.iter().filter(|b| members.contains(&b.block));
let mut g = Group {
blocks: members.clone(),
top: f32::INFINITY,
bottom: f32::NEG_INFINITY,
left: f32::INFINITY,
right: f32::NEG_INFINITY,
size: 0.0,
};
for b in bx {
g.top = g.top.min(b.top);
g.bottom = g.bottom.max(b.bottom);
g.left = g.left.min(b.left);
g.right = g.right.max(b.right);
g.size = g.size.max(b.size);
}
groups.push(g);
}
groups.sort_by(|a, b| a.top.total_cmp(&b.top));
let mut merged: Vec<Group> = Vec::new();
for g in groups {
if let Some(m) = merged.last_mut()
&& g.top - m.bottom <= MERGE_GAP * m.size.max(g.size)
&& g.left < m.right
&& m.left < g.right
{
m.blocks.extend(g.blocks);
m.top = m.top.min(g.top);
m.bottom = m.bottom.max(g.bottom);
m.left = m.left.min(g.left);
m.right = m.right.max(g.right);
m.size = m.size.max(g.size);
continue;
}
merged.push(g);
}
let mut out = Vec::new();
for mut g in merged {
for &b in ids {
if g.blocks.contains(&b) {
continue;
}
let inside = boxes.iter().filter(|x| x.block == b).all(|x| {
x.top >= g.top - ROW_OVERLAP * g.size
&& x.bottom <= g.bottom + ROW_OVERLAP * g.size
&& x.left >= g.left - ROW_OVERLAP * g.size
&& x.right <= g.right + ROW_OVERLAP * g.size
});
if inside {
g.blocks.push(b);
}
}
loop {
let next = ids.iter().copied().find(|&b| {
let mut bx = boxes.iter().filter(|x| x.block == b);
!g.blocks.contains(&b)
&& bx.clone().count() == 1
&& bx.next().is_some_and(|x| {
let tol = CONT_ALIGN * x.size;
x.top >= g.bottom - ROW_OVERLAP * x.size
&& x.top - g.bottom <= CONT_GAP * x.size
&& x.left > g.left + tol
&& x.right <= g.right + tol
&& boxes.iter().any(|y| {
g.blocks.contains(&y.block) && (y.left - x.left).abs() <= tol
})
})
});
let Some(b) = next else { break };
g.blocks.push(b);
if let Some(x) = boxes.iter().find(|x| x.block == b) {
g.bottom = g.bottom.max(x.bottom);
}
}
g.blocks.sort_unstable();
g.blocks.dedup();
out.push(g.blocks);
}
out
}
struct Phys {
baseline: f32,
words: Vec<Word>,
splits: Vec<(f32, f32)>,
}
fn phys_rows(lines: &[(usize, &crate::layout::Line)]) -> Vec<Phys> {
let mut ls: Vec<&(usize, &crate::layout::Line)> = lines.iter().collect();
ls.sort_by(|a, b| a.1.baseline.total_cmp(&b.1.baseline));
let mut rows: Vec<(f32, Vec<&(usize, &crate::layout::Line)>)> = Vec::new();
for x in ls {
match rows.last_mut() {
Some((base, v)) if x.1.baseline - *base <= BASELINE_TOL * x.1.size => v.push(x),
_ => rows.push((x.1.baseline, vec![x])),
}
}
rows.into_iter()
.map(|(baseline, mut v)| {
v.sort_by(|a, b| a.1.bbox.left.total_cmp(&b.1.bbox.left));
let splits = v
.windows(2)
.filter(|p| p[0].0 != p[1].0 && p[0].1.bbox.right <= p[1].1.bbox.left)
.map(|p| (p[0].1.bbox.right, p[1].1.bbox.left))
.collect();
let mut words: Vec<Word> = v.iter().flat_map(|x| x.1.words.iter().cloned()).collect();
words.sort_by(|a, b| a.bbox.left.total_cmp(&b.bbox.left));
Phys {
baseline,
words,
splits,
}
})
.collect()
}
fn dominant_size(rows: &[Phys]) -> f32 {
let mut sizes: Vec<(f32, usize)> = Vec::new();
for w in rows.iter().flat_map(|r| &r.words) {
match sizes.iter_mut().find(|(s, _)| (s - w.size).abs() < 0.05) {
Some((_, n)) => *n += w.len.max(1),
None => sizes.push((w.size, w.len.max(1))),
}
}
sizes
.iter()
.max_by(|a, b| a.1.cmp(&b.1).then(b.0.total_cmp(&a.0)))
.map_or(0.0, |(s, _)| *s)
}
fn gutters(rows: &[Phys], min: f32) -> Vec<(f32, f32)> {
let mut spans: Vec<(f32, f32)> = rows
.iter()
.flat_map(|r| &r.words)
.filter(|w| !w.text.trim().is_empty())
.map(|w| (w.bbox.left, w.bbox.right))
.collect();
spans.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut out = Vec::new();
let mut reach = f32::NEG_INFINITY;
for (l, r) in spans {
if reach.is_finite() && l - reach >= min {
out.push((reach, l));
}
reach = reach.max(r);
}
out
}
fn column_of(w: &Word, bounds: &[f32]) -> usize {
let x = w.bbox.center_x();
bounds.iter().take_while(|&&b| x > b).count()
}
fn split_cols(rows: &[Phys], bounds: &[f32]) -> Vec<Vec<Vec<Word>>> {
rows.iter()
.map(|r| {
let mut cols = vec![Vec::new(); bounds.len() + 1];
for w in &r.words {
cols[column_of(w, bounds)].push(w.clone());
}
cols
})
.collect()
}
fn is_numeric(words: &[Word]) -> bool {
let mut digit = false;
for c in words.iter().flat_map(|w| w.text.chars()) {
if c.is_ascii_digit() {
digit = true;
} else if !".,%+-−()$€R/".contains(c) {
return false;
}
}
digit
}
fn filled<'a>(
rows: &'a [Phys],
cols: &'a [Vec<Vec<Word>>],
c: usize,
) -> impl Iterator<Item = f32> + 'a {
rows.iter()
.zip(cols)
.filter(move |(_, cs)| cs.get(c).is_some_and(|ws| !ws.is_empty()))
.map(|(r, _)| r.baseline)
}
fn logical_rows(rows: &[Phys], cols: &[Vec<Vec<Word>>], size: f32) -> Vec<(usize, usize)> {
let ncols = cols.first().map_or(0, Vec::len);
let mut steps = Vec::new();
for c in 0..ncols {
let mut prev: Option<f32> = None;
for b in filled(rows, cols, c) {
if let Some(p) = prev
&& b - p > MIN_STEP * size
{
steps.push(b - p);
}
prev = Some(b);
}
}
steps.sort_by(f32::total_cmp);
let (Some(&s_min), Some(&s_med)) = (steps.first(), steps.get(steps.len() / 2)) else {
return (0..rows.len()).map(|r| (r, r)).collect();
};
if s_med > GAPPED_RATIO * s_min {
let mut spans: Vec<(f32, f32)> = Vec::new();
for c in 0..ncols {
let mut cur: Option<(f32, f32)> = None;
for b in filled(rows, cols, c) {
cur = match cur {
Some((t, e)) if b - e <= CELL_CHAIN * s_min => Some((t, b)),
Some(span) => {
spans.push(span);
Some((b, b))
}
None => Some((b, b)),
};
}
spans.extend(cur);
}
let mut cores: Vec<(f32, f32)> = spans
.iter()
.map(|(t, e)| (t - CORE_ASCENT * size, e + CORE_DESCENT * size))
.collect();
cores.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut bands: Vec<(f32, f32)> = Vec::new();
for c in cores {
match bands.last_mut() {
Some(b) if c.0 < b.1 => b.1 = b.1.max(c.1),
_ => bands.push(c),
}
}
let mut out: Vec<(usize, usize)> = Vec::new();
for (r, row) in rows.iter().enumerate() {
let band = bands
.iter()
.position(|b| row.baseline >= b.0 && row.baseline <= b.1);
match (out.last_mut(), band) {
(Some(last), Some(k)) if band_of(&bands, rows, last.0) == Some(k) => last.1 = r,
_ => out.push((r, r)),
}
}
return out;
}
let mut out: Vec<(usize, usize)> = Vec::new();
for r in 0..rows.len() {
let cont = out.last().is_some_and(|&(a, b)| {
let here = &cols[r];
let filled = |c: usize| (a..=b).any(|k| !cols[k][c].is_empty());
here.first().is_some_and(Vec::is_empty)
&& here
.iter()
.enumerate()
.all(|(c, ws)| ws.is_empty() || filled(c) && !is_numeric(ws))
});
match out.last_mut() {
Some(last) if cont => last.1 = r,
_ => out.push((r, r)),
}
}
out
}
fn band_of(bands: &[(f32, f32)], rows: &[Phys], r: usize) -> Option<usize> {
let b = rows.get(r)?.baseline;
bands.iter().position(|x| b >= x.0 && b <= x.1)
}
fn cells(cols: &[Vec<Vec<Word>>], logical: &[(usize, usize)]) -> Vec<Vec<Cell>> {
let ncols = cols.first().map_or(0, Vec::len);
logical
.iter()
.map(|&(a, b)| {
(0..ncols)
.map(|c| {
(a..=b)
.filter(|&r| !cols[r][c].is_empty())
.map(|r| cols[r][c].clone())
.collect()
})
.collect()
})
.collect()
}
fn cell_edges(cell: &Cell) -> Option<(f32, f32)> {
let ws = cell.iter().flatten();
let l = ws.clone().map(|w| w.bbox.left).reduce(f32::min)?;
let r = ws.map(|w| w.bbox.right).reduce(f32::max)?;
Some((l, r))
}
#[derive(Clone, Copy, Default, Debug)]
struct Aligned {
left: bool,
right: bool,
center: bool,
}
fn alignment(grid: &[Vec<Cell>], c: usize, tol: f32) -> Aligned {
let edges: Vec<(f32, f32)> = grid
.iter()
.filter_map(|row| row.get(c).and_then(cell_edges))
.collect();
if edges.len() < 2 {
return Aligned::default();
}
let spread = |f: &dyn Fn(&(f32, f32)) -> f32| {
let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
for e in &edges {
lo = lo.min(f(e));
hi = hi.max(f(e));
}
hi - lo
};
Aligned {
left: spread(&|e| e.0) <= tol,
right: spread(&|e| e.1) <= tol,
center: spread(&|e| (e.0 + e.1) / 2.0) <= tol,
}
}
fn both(grid: &[Vec<Cell>], c: usize) -> usize {
grid.iter()
.filter(|row| {
row.get(c).is_some_and(|x| !x.is_empty())
&& row.get(c + 1).is_some_and(|x| !x.is_empty())
})
.count()
}
fn supported(grid: &[Vec<Cell>], c: usize, ncols: usize, tol: f32) -> bool {
if both(grid, c) < MIN_BOTH {
return false;
}
let a = alignment(grid, c, tol);
let b = alignment(grid, c + 1, tol);
a.right || a.center || a.left && c > 0 || b.left || b.center || b.right && c + 1 < ncols - 1
}
fn has_inner_gap(cell: &Cell) -> bool {
cell.iter().any(|line| {
line.windows(2)
.any(|p| p[1].bbox.left - p[0].bbox.right > LINE_SPLIT_GAP * p[0].size.max(p[1].size))
})
}
fn analyze(lines: &[(usize, &crate::layout::Line)]) -> Option<Body> {
let rows = phys_rows(lines);
if rows.iter().filter(|r| !r.splits.is_empty()).count() < MIN_MULTI_ROWS {
return None;
}
let size = dominant_size(&rows);
if size <= 0.0 {
return None;
}
let tol = (ALIGN_EM * size).max(ALIGN_MIN_PT);
let mut gaps = gutters(&rows, MIN_GUTTER * size);
let in_gutter = |s: &(f32, f32)| gaps.iter().any(|g| s.0 < g.1 && g.0 < s.1);
if rows
.iter()
.filter(|r| r.splits.iter().any(in_gutter))
.count()
< MIN_MULTI_ROWS
{
return None;
}
let mut rejected = false;
let grid = loop {
let bounds: Vec<f32> = gaps.iter().map(|(l, r)| (l + r) / 2.0).collect();
let cols = split_cols(&rows, &bounds);
let logical = logical_rows(&rows, &cols, size);
let grid = cells(&cols, &logical);
let ncols = bounds.len() + 1;
let bad = (0..bounds.len())
.filter(|&c| !supported(&grid, c, ncols, tol))
.min_by(|&x, &y| {
both(&grid, x)
.cmp(&both(&grid, y))
.then((gaps[x].1 - gaps[x].0).total_cmp(&(gaps[y].1 - gaps[y].0)))
});
match bad {
Some(c) => {
gaps.remove(c);
rejected = true;
}
None => break grid,
}
};
let ncols = gaps.len() + 1;
let certain = !rejected
&& ncols >= 2
&& grid.len() >= MIN_MULTI_ROWS
&& !grid.iter().flatten().any(has_inner_gap);
if certain {
let align = (0..ncols)
.map(|c| {
let a = alignment(&grid, c, tol);
let numeric = grid
.iter()
.skip(1)
.filter_map(|row| row.get(c))
.filter(|x| !x.is_empty())
.all(|x| x.iter().all(|l| is_numeric(l)));
match (a.left, a.right, a.center) {
(_, true, _) if numeric => Align::Right,
(true, _, _) => Align::Left,
(false, true, _) => Align::Right,
(false, false, true) => Align::Center,
_ if numeric => Align::Right,
_ => Align::Left,
}
})
.collect();
return Some(Body::Grid { align, rows: grid });
}
Some(Body::Layout {
rows: rows.into_iter().map(|r| r.words).collect(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::{Line, Rect, Region, Style};
const SIZE: f32 = 10.0;
fn words(text: &str, x: f32, base: f32) -> Vec<Word> {
let mut out = Vec::new();
let mut x = x;
for t in text.split(' ') {
let w = 0.5 * SIZE * t.chars().count() as f32;
out.push(Word {
text: t.into(),
bbox: Rect::new(x, base - 0.9 * SIZE, x + w, base + 0.25 * SIZE),
baseline: base,
size: SIZE,
font: "Serif".into(),
style: Style::default(),
glued: false,
len: t.chars().count(),
chars: 0..0,
figure: None,
});
x += w + 0.25 * SIZE;
}
out
}
fn line(text: &str, x: f32, base: f32) -> Line {
let ws = words(text, x, base);
let bbox = ws.iter().skip(1).fold(ws[0].bbox, |a, w| a.union(&w.bbox));
Line {
words: ws,
bbox,
baseline: base,
size: SIZE,
style: Style::default(),
}
}
fn block(lines: &[(&str, f32, f32)]) -> Block {
let lines: Vec<Line> = lines.iter().map(|&(t, x, b)| line(t, x, b)).collect();
let bbox = lines
.iter()
.skip(1)
.fold(lines[0].bbox, |a, l| a.union(&l.bbox));
Block {
lines,
bbox,
size: SIZE,
style: Style::default(),
region: 0,
}
}
fn page(blocks: Vec<Block>) -> Page {
Page {
number: 1,
width: 600.0,
height: 800.0,
regions: vec![Region {
rect: Rect::new(50.0, 50.0, 550.0, 750.0),
band: 0,
column: 0,
columns: 1,
}],
blocks,
furniture: Vec::new(),
chars: Vec::new(),
}
}
fn texts(cell: &Cell) -> String {
cell.iter()
.flatten()
.map(|w| w.text.as_str())
.collect::<Vec<_>>()
.join(" ")
}
fn r(text: &str, right: f32) -> f32 {
right - 0.5 * SIZE * text.chars().count() as f32
}
fn y(i: usize) -> f32 {
100.0 + 12.0 * i as f32
}
fn grid(t: &Table) -> (&[Align], Vec<Vec<String>>) {
match &t.body {
Body::Grid { align, rows } => (
align,
rows.iter()
.map(|row| row.iter().map(texts).collect())
.collect(),
),
Body::Layout { .. } => panic!("expected a grid, got a layout"),
}
}
fn column(v: &[&str], x: impl Fn(&str) -> f32) -> Block {
let ls: Vec<(&str, f32, f32)> = v
.iter()
.enumerate()
.map(|(i, t)| (*t, x(t), y(i)))
.collect();
block(&ls)
}
#[test]
fn three_columns_left_right_left() {
let p = page(vec![
column(&["Item", "Cimento", "Areia", "Brita", "Tijolo"], |_| 50.0),
column(&["Qtd", "120", "18", "22", "9.500"], |t| r(t, 200.0)),
column(&["Unidade", "sacos", "m3", "m3", "unidades"], |_| 220.0),
]);
let ts = detect(&p, |_| true);
assert_eq!(ts.len(), 1);
assert_eq!(ts[0].blocks, vec![0, 1, 2]);
let (align, rows) = grid(&ts[0]);
assert_eq!(align, [Align::Left, Align::Right, Align::Left]);
assert_eq!(rows[0], ["Item", "Qtd", "Unidade"]);
assert_eq!(rows[4], ["Tijolo", "9.500", "unidades"]);
}
#[test]
fn justified_paragraph_is_not_a_table() {
let p = page(vec![block(&[
(
"Responsabilidades extraordinariamente desproporcionais",
50.0,
y(0),
),
(
"inconstitucionalidades procedimentos administrativos",
50.0,
y(1),
),
(
"otorrinolaringologista paralelepipedos desenvolvimento",
50.0,
y(2),
),
("superintendencia regional fundamentalmente", 50.0, y(3)),
])]);
assert!(detect(&p, |_| true).is_empty());
}
#[test]
fn fragments_split_off_prose_lines_are_not_a_table() {
let bs = vec![
block(&[
("aaaa bbbb cccc dddd", 50.0, y(0)),
("aaaa bbbb cccc dddd eeee ffff gggg hhhh", 50.0, y(1)),
("aaaa bbbb", 50.0, y(2)),
("aaaa bbbb cccc dddd eeee ffff gggg hhhh", 50.0, y(3)),
("aaaa bbbb cccc", 50.0, y(4)),
]),
block(&[("xx", 170.0, y(0))]),
block(&[("yy", 120.0, y(2))]),
block(&[("zz", 140.0, y(4))]),
];
assert!(detect(&page(bs), |_| true).is_empty());
}
#[test]
fn continuation_rows_join_but_empty_first_cells_with_numbers_do_not() {
let p = page(vec![
block(&[
("Regiao", 50.0, y(0)),
("Sul", 50.0, y(1)),
("Norte", 50.0, y(4)),
]),
block(&[
("Estado", 120.0, y(0)),
("Parana", 120.0, y(1)),
("Goias", 120.0, y(2)),
("Bahia", 120.0, y(4)),
]),
block(&[
("Total", r("Total", 260.0), y(0)),
("10", r("10", 260.0), y(1)),
("20", r("20", 260.0), y(2)),
("40", r("40", 260.0), y(4)),
]),
block(&[
("Nota", 280.0, y(0)),
("Documento de", 280.0, y(1)),
("escritorio", 280.0, y(2)),
("x", 280.0, y(3)),
("fim", 280.0, y(4)),
]),
]);
let ts = detect(&p, |_| true);
assert_eq!(ts.len(), 1);
let (_, rows) = grid(&ts[0]);
assert_eq!(rows.len(), 4);
assert_eq!(rows[2], ["", "Goias", "20", "escritorio x"]);
assert_eq!(rows[3], ["Norte", "Bahia", "40", "fim"]);
}
#[test]
fn wrapped_cells_with_a_smaller_pitch_make_one_row() {
let first = block(&[
("Etapa", 50.0, 100.0),
("1", 50.0, 136.75),
("2", 50.0, 170.0),
("3", 50.0, 200.0),
]);
let second = block(&[
("Descricao", 100.0, 100.0),
("Levantamento dos", 100.0, 130.0),
("documentos antigos", 100.0, 143.5),
("Digitalizacao", 100.0, 170.0),
("Publicacao", 100.0, 200.0),
]);
let third = block(&[
("Prazo", 250.0, 100.0),
("15 dias", 250.0, 136.75),
("30 dias", 250.0, 170.0),
("5 dias", 250.0, 200.0),
]);
let ts = detect(&page(vec![first, second, third]), |_| true);
assert_eq!(ts.len(), 1);
let (_, rows) = grid(&ts[0]);
assert_eq!(rows.len(), 4);
assert_eq!(
rows[1],
["1", "Levantamento dos documentos antigos", "15 dias"]
);
}
#[test]
fn a_cell_spanning_a_boundary_gives_a_layout() {
let a = |t: &str| r(t, 150.0);
let b = |t: &str| r(t, 210.0);
let p = page(vec![
column(
&["Indicador", "Receita", "Despesa", "Investimento", "Margem"],
|_| 50.0,
),
block(&[("2023", a("2023"), y(0)), ("1.240,5", a("1.240,5"), y(1))]),
block(&[("2024", b("2024"), y(0)), ("1.318,2", b("1.318,2"), y(1))]),
block(&[("980,1", a("980,1"), y(2))]),
block(&[("1.002,7", b("1.002,7"), y(2))]),
block(&[("sem investimento", b("sem investimento"), y(3))]),
block(&[("21,0", a("21,0"), y(4))]),
block(&[("23,9", b("23,9"), y(4))]),
]);
let ts = detect(&p, |_| true);
assert_eq!(ts.len(), 1);
let Body::Layout { rows } = &ts[0].body else {
panic!("expected a layout");
};
assert_eq!(rows.len(), 5);
assert_eq!(ts[0].blocks.len(), 8);
}
#[test]
fn ineligible_blocks_are_left_alone() {
let p = page(vec![
column(&["a", "b", "c"], |_| 50.0),
column(&["1", "2", "3"], |_| 100.0),
]);
assert_eq!(detect(&p, |_| true).len(), 1);
assert!(detect(&p, |i| i != 1).is_empty());
}
}