| 1 | use serde::{Deserialize, Serialize}; |
| 2 | |
| 3 | use crate::markdown::escape_html; |
| 4 | |
| 5 | pub const TABLE_MARK: char = '\u{FFFB}'; |
| 6 | pub const PICKER_COLUMNS: usize = 7; |
| 7 | pub const PICKER_ROWS: usize = 5; |
| 8 | const EMPTY_CELL: &str = " "; |
| 9 | |
| 10 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 11 | pub struct Cell { |
| 12 | pub row: usize, |
| 13 | pub column: usize, |
| 14 | } |
| 15 | |
| 16 | impl Cell { |
| 17 | pub fn new(row: usize, column: usize) -> Cell { |
| 18 | Cell { row, column } |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | /// A composer table: plain text cells, every row as wide as the first. |
| 23 | #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 24 | pub struct Table { |
| 25 | pub rows: Vec<Vec<String>>, |
| 26 | } |
| 27 | |
| 28 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 29 | pub enum TableEdit { |
| 30 | InsertRowAbove, |
| 31 | InsertRowBelow, |
| 32 | InsertColumnLeft, |
| 33 | InsertColumnRight, |
| 34 | DeleteRow, |
| 35 | DeleteColumn, |
| 36 | DeleteTable, |
| 37 | } |
| 38 | |
| 39 | impl TableEdit { |
| 40 | pub const INSERTS: [TableEdit; 4] = [ |
| 41 | TableEdit::InsertRowAbove, |
| 42 | TableEdit::InsertRowBelow, |
| 43 | TableEdit::InsertColumnLeft, |
| 44 | TableEdit::InsertColumnRight, |
| 45 | ]; |
| 46 | pub const DELETES: [TableEdit; 3] = [ |
| 47 | TableEdit::DeleteRow, |
| 48 | TableEdit::DeleteColumn, |
| 49 | TableEdit::DeleteTable, |
| 50 | ]; |
| 51 | |
| 52 | pub fn label(self) -> &'static str { |
| 53 | match self { |
| 54 | TableEdit::InsertRowAbove => "Insert row above", |
| 55 | TableEdit::InsertRowBelow => "Insert row below", |
| 56 | TableEdit::InsertColumnLeft => "Insert column to the left", |
| 57 | TableEdit::InsertColumnRight => "Insert column to the right", |
| 58 | TableEdit::DeleteRow => "Delete row", |
| 59 | TableEdit::DeleteColumn => "Delete column", |
| 60 | TableEdit::DeleteTable => "Delete table", |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | impl Table { |
| 66 | pub fn new(rows: usize, columns: usize) -> Table { |
| 67 | Table { |
| 68 | rows: vec![vec![String::new(); columns.max(1)]; rows.max(1)], |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// Short rows are filled up to the widest one. |
| 73 | pub fn from_rows(mut rows: Vec<Vec<String>>) -> Table { |
| 74 | rows.retain(|row| !row.is_empty()); |
| 75 | let columns = rows.iter().map(Vec::len).max().unwrap_or(1); |
| 76 | for row in &mut rows { |
| 77 | row.resize(columns, String::new()); |
| 78 | } |
| 79 | if rows.is_empty() { |
| 80 | return Table::new(1, 1); |
| 81 | } |
| 82 | Table { rows } |
| 83 | } |
| 84 | |
| 85 | pub fn row_count(&self) -> usize { |
| 86 | self.rows.len() |
| 87 | } |
| 88 | |
| 89 | pub fn column_count(&self) -> usize { |
| 90 | self.rows.first().map_or(0, Vec::len) |
| 91 | } |
| 92 | |
| 93 | pub fn cell(&self, cell: Cell) -> Option<&str> { |
| 94 | self.rows |
| 95 | .get(cell.row)? |
| 96 | .get(cell.column) |
| 97 | .map(String::as_str) |
| 98 | } |
| 99 | |
| 100 | pub fn set_cell(&mut self, cell: Cell, text: &str) { |
| 101 | if let Some(slot) = self |
| 102 | .rows |
| 103 | .get_mut(cell.row) |
| 104 | .and_then(|row| row.get_mut(cell.column)) |
| 105 | { |
| 106 | *slot = text.to_owned(); |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | pub fn last_cell(&self) -> Cell { |
| 111 | Cell::new(self.row_count() - 1, self.column_count() - 1) |
| 112 | } |
| 113 | |
| 114 | /// Tab: the next cell, and past the last one a new row (`true`) like Teams. |
| 115 | pub fn next_cell(&mut self, cell: Cell) -> (Cell, bool) { |
| 116 | if cell.column + 1 < self.column_count() { |
| 117 | return (Cell::new(cell.row, cell.column + 1), false); |
| 118 | } |
| 119 | if cell.row + 1 < self.row_count() { |
| 120 | return (Cell::new(cell.row + 1, 0), false); |
| 121 | } |
| 122 | self.rows.push(vec![String::new(); self.column_count()]); |
| 123 | (Cell::new(cell.row + 1, 0), true) |
| 124 | } |
| 125 | |
| 126 | /// Shift+Tab: the previous cell; the first cell stays. |
| 127 | pub fn previous_cell(&self, cell: Cell) -> Cell { |
| 128 | match (cell.row, cell.column) { |
| 129 | (_, column) if column > 0 => Cell::new(cell.row, column - 1), |
| 130 | (0, _) => cell, |
| 131 | (row, _) => Cell::new(row - 1, self.column_count() - 1), |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | /// The cell to focus afterwards; `None` when the table is gone. |
| 136 | pub fn apply(&mut self, edit: TableEdit, cell: Cell) -> Option<Cell> { |
| 137 | let columns = self.column_count(); |
| 138 | match edit { |
| 139 | TableEdit::InsertRowAbove => { |
| 140 | self.rows.insert(cell.row, vec![String::new(); columns]); |
| 141 | Some(Cell::new(cell.row, cell.column)) |
| 142 | } |
| 143 | TableEdit::InsertRowBelow => { |
| 144 | self.rows.insert(cell.row + 1, vec![String::new(); columns]); |
| 145 | Some(Cell::new(cell.row + 1, cell.column)) |
| 146 | } |
| 147 | TableEdit::InsertColumnLeft => { |
| 148 | for row in &mut self.rows { |
| 149 | row.insert(cell.column, String::new()); |
| 150 | } |
| 151 | Some(Cell::new(cell.row, cell.column)) |
| 152 | } |
| 153 | TableEdit::InsertColumnRight => { |
| 154 | for row in &mut self.rows { |
| 155 | row.insert(cell.column + 1, String::new()); |
| 156 | } |
| 157 | Some(Cell::new(cell.row, cell.column + 1)) |
| 158 | } |
| 159 | TableEdit::DeleteRow if self.row_count() > 1 => { |
| 160 | self.rows.remove(cell.row); |
| 161 | Some(Cell::new(cell.row.min(self.row_count() - 1), cell.column)) |
| 162 | } |
| 163 | TableEdit::DeleteColumn if columns > 1 => { |
| 164 | for row in &mut self.rows { |
| 165 | row.remove(cell.column); |
| 166 | } |
| 167 | Some(Cell::new( |
| 168 | cell.row, |
| 169 | cell.column.min(self.column_count() - 1), |
| 170 | )) |
| 171 | } |
| 172 | TableEdit::DeleteRow | TableEdit::DeleteColumn | TableEdit::DeleteTable => None, |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | pub fn is_blank(&self) -> bool { |
| 177 | self.rows |
| 178 | .iter() |
| 179 | .flatten() |
| 180 | .all(|cell| cell.trim().is_empty()) |
| 181 | } |
| 182 | |
| 183 | /// Rows on lines, cells split by tabs: what a spreadsheet pastes. |
| 184 | pub fn plain_text(&self) -> String { |
| 185 | self.rows |
| 186 | .iter() |
| 187 | .map(|row| row.join("\t").replace('\n', " ")) |
| 188 | .collect::<Vec<_>>() |
| 189 | .join("\n") |
| 190 | } |
| 191 | |
| 192 | /// The table Teams sends: CKEditor's `figure.table`, `copy-paste-table` on the table, a one |
| 193 | /// line cell without `<p>`, every line of a longer cell in its own `<p>`, empty ` `. |
| 194 | pub fn to_html(&self) -> String { |
| 195 | let mut html = |
| 196 | String::from("<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>"); |
| 197 | for row in &self.rows { |
| 198 | html.push_str("<tr>"); |
| 199 | for cell in row { |
| 200 | html.push_str("<td>"); |
| 201 | if cell.trim().is_empty() { |
| 202 | html.push_str(EMPTY_CELL); |
| 203 | } else if !cell.contains('\n') { |
| 204 | html.push_str(&escape_html(cell)); |
| 205 | } else { |
| 206 | for line in cell.split('\n') { |
| 207 | html.push_str("<p>"); |
| 208 | if line.trim().is_empty() { |
| 209 | html.push_str(EMPTY_CELL); |
| 210 | } else { |
| 211 | html.push_str(&escape_html(line)); |
| 212 | } |
| 213 | html.push_str("</p>"); |
| 214 | } |
| 215 | } |
| 216 | html.push_str("</td>"); |
| 217 | } |
| 218 | html.push_str("</tr>"); |
| 219 | } |
| 220 | html.push_str("</tbody></table></figure>"); |
| 221 | html |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | fn split_row(line: &str) -> Option<Vec<String>> { |
| 226 | let trimmed = line.trim(); |
| 227 | if !trimmed.contains('|') { |
| 228 | return None; |
| 229 | } |
| 230 | let inner = trimmed.strip_prefix('|').unwrap_or(trimmed); |
| 231 | let inner = inner.strip_suffix('|').unwrap_or(inner); |
| 232 | let mut cells = Vec::new(); |
| 233 | let mut current = String::new(); |
| 234 | let mut characters = inner.chars().peekable(); |
| 235 | while let Some(character) = characters.next() { |
| 236 | match character { |
| 237 | '\\' if characters.peek() == Some(&'|') => { |
| 238 | current.push('|'); |
| 239 | characters.next(); |
| 240 | } |
| 241 | '|' => cells.push(std::mem::take(&mut current).trim().to_owned()), |
| 242 | other => current.push(other), |
| 243 | } |
| 244 | } |
| 245 | cells.push(current.trim().to_owned()); |
| 246 | Some(cells) |
| 247 | } |
| 248 | |
| 249 | fn is_delimiter_row(line: &str) -> bool { |
| 250 | split_row(line).is_some_and(|cells| { |
| 251 | cells.iter().all(|cell| { |
| 252 | let dashes = cell.trim_start_matches(':').trim_end_matches(':'); |
| 253 | !dashes.is_empty() && dashes.chars().all(|character| character == '-') |
| 254 | }) |
| 255 | }) |
| 256 | } |
| 257 | |
| 258 | /// A GitHub markdown table at the start of `lines`: header, delimiter row, body rows. |
| 259 | /// Returns the raw cell sources and how many lines it spans. |
| 260 | pub(crate) fn markdown_table(lines: &[&str]) -> Option<(Vec<Vec<String>>, usize)> { |
| 261 | let header = split_row(lines.first()?)?; |
| 262 | if !lines.get(1).is_some_and(|line| is_delimiter_row(line)) { |
| 263 | return None; |
| 264 | } |
| 265 | let delimiter_columns = split_row(lines[1])?.len(); |
| 266 | if delimiter_columns != header.len() { |
| 267 | return None; |
| 268 | } |
| 269 | let mut rows = vec![header]; |
| 270 | let mut consumed = 2; |
| 271 | for line in &lines[2..] { |
| 272 | match split_row(line) { |
| 273 | Some(cells) if !line.trim().is_empty() => rows.push(cells), |
| 274 | _ => break, |
| 275 | } |
| 276 | consumed += 1; |
| 277 | } |
| 278 | Some((rows, consumed)) |
| 279 | } |
| 280 | |
| 281 | #[cfg(test)] |
| 282 | mod tests { |
| 283 | use super::*; |
| 284 | |
| 285 | #[test] |
| 286 | fn tab_walks_the_cells_and_adds_a_row_after_the_last() { |
| 287 | let mut table = Table::new(2, 2); |
| 288 | assert_eq!(table.next_cell(Cell::new(0, 0)), (Cell::new(0, 1), false)); |
| 289 | assert_eq!(table.next_cell(Cell::new(0, 1)), (Cell::new(1, 0), false)); |
| 290 | assert_eq!(table.next_cell(Cell::new(1, 1)), (Cell::new(2, 0), true)); |
| 291 | assert_eq!(table.row_count(), 3); |
| 292 | assert_eq!(table.column_count(), 2); |
| 293 | } |
| 294 | |
| 295 | #[test] |
| 296 | fn shift_tab_walks_back_and_stops_at_the_first_cell() { |
| 297 | let table = Table::new(2, 3); |
| 298 | assert_eq!(table.previous_cell(Cell::new(1, 0)), Cell::new(0, 2)); |
| 299 | assert_eq!(table.previous_cell(Cell::new(0, 1)), Cell::new(0, 0)); |
| 300 | assert_eq!(table.previous_cell(Cell::new(0, 0)), Cell::new(0, 0)); |
| 301 | } |
| 302 | |
| 303 | #[test] |
| 304 | fn rows_and_columns_insert_and_delete_around_the_cell() { |
| 305 | let mut table = Table::from_rows(vec![ |
| 306 | vec!["a".into(), "b".into()], |
| 307 | vec!["c".into(), "d".into()], |
| 308 | ]); |
| 309 | assert_eq!( |
| 310 | table.apply(TableEdit::InsertRowAbove, Cell::new(1, 1)), |
| 311 | Some(Cell::new(1, 1)) |
| 312 | ); |
| 313 | assert_eq!(table.rows[1], ["", ""]); |
| 314 | assert_eq!( |
| 315 | table.apply(TableEdit::InsertColumnRight, Cell::new(0, 0)), |
| 316 | Some(Cell::new(0, 1)) |
| 317 | ); |
| 318 | assert_eq!(table.rows[0], ["a", "", "b"]); |
| 319 | table.apply(TableEdit::DeleteColumn, Cell::new(0, 1)); |
| 320 | table.apply(TableEdit::DeleteRow, Cell::new(1, 0)); |
| 321 | assert_eq!(table.rows, [["a", "b"], ["c", "d"]]); |
| 322 | assert_eq!(table.apply(TableEdit::DeleteTable, Cell::new(0, 0)), None); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn deleting_the_last_row_or_column_deletes_the_table() { |
| 327 | let mut table = Table::new(1, 2); |
| 328 | assert_eq!(table.apply(TableEdit::DeleteRow, Cell::new(0, 0)), None); |
| 329 | let mut table = Table::new(2, 1); |
| 330 | assert_eq!(table.apply(TableEdit::DeleteColumn, Cell::new(0, 0)), None); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn html_is_the_copy_paste_table_teams_sends() { |
| 335 | let table = Table::from_rows(vec![vec!["a<b".into(), String::new()], vec!["x\ny".into()]]); |
| 336 | assert_eq!( |
| 337 | table.to_html(), |
| 338 | "<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\ |
| 339 | <tr><td>a<b</td><td> </td></tr>\ |
| 340 | <tr><td><p>x</p><p>y</p></td><td> </td></tr></tbody></table></figure>" |
| 341 | ); |
| 342 | } |
| 343 | |
| 344 | #[test] |
| 345 | fn markdown_tables_need_a_delimiter_row() { |
| 346 | let lines = ["| A | B |", "|---|:-:|", "| 1 | 2 \\| 3 |", "", "after"]; |
| 347 | let (rows, consumed) = markdown_table(&lines).unwrap(); |
| 348 | assert_eq!(consumed, 3); |
| 349 | assert_eq!(rows, [["A", "B"], ["1", "2 | 3"]]); |
| 350 | assert!(markdown_table(&["a | b", "c | d"]).is_none()); |
| 351 | assert!(markdown_table(&["| a | b |", "|---|"]).is_none()); |
| 352 | } |
| 353 | } |