use crate::extraction::{cells_to_markdown, cells_to_text};
use crate::types::Table;
pub struct TableState {
pub rows: Vec<Vec<String>>,
pub current_row: Vec<String>,
pub current_cell: String,
pub in_row: bool,
}
impl TableState {
pub fn new() -> Self {
Self {
rows: Vec::new(),
current_row: Vec::new(),
current_cell: String::new(),
in_row: false,
}
}
pub fn push_cell(&mut self) {
let cell = self.current_cell.trim().to_string();
self.current_row.push(cell);
self.current_cell.clear();
}
pub fn push_row(&mut self) {
if self.in_row || !self.current_cell.is_empty() {
self.push_cell();
self.in_row = false;
}
if !self.current_row.is_empty() {
self.rows.push(self.current_row.clone());
self.current_row.clear();
}
}
pub fn start_row(&mut self) {
if self.in_row {
self.push_row();
}
self.in_row = true;
self.current_cell.clear();
self.current_row.clear();
}
pub fn finalize_with_format(mut self, plain: bool) -> Option<Table> {
if self.in_row || !self.current_cell.is_empty() || !self.current_row.is_empty() {
self.push_row();
}
if self.rows.is_empty() {
return None;
}
let markdown = if plain {
cells_to_text(&self.rows)
} else {
cells_to_markdown(&self.rows)
};
Some(Table {
cells: self.rows,
markdown,
page_number: 1,
bounding_box: None,
})
}
}
impl Default for TableState {
fn default() -> Self {
Self::new()
}
}