Skip to content

Commit 3502858

Browse files
committed
Table: address review feedback on vertical merges and colgroups (#5906)
1 parent 17175bc commit 3502858

6 files changed

Lines changed: 278 additions & 21 deletions

File tree

β€Žcrates/doc/src/edit.rsβ€Ž

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -571,15 +571,33 @@ fn trim_para(para: &Paragraph, from: usize, to: usize, clear_section: bool) -> P
571571
p
572572
}
573573

574-
/// The grid column span `(g0, g1)` of cell `(r, c)` in `table`.
574+
/// Return the inclusive grid column bounds `(g0, g1)` covered by cell `(r, c)` in `table`.
575+
///
576+
/// Coordinate systems:
577+
/// - `r` is a 0-based row index into `table.rows`.
578+
/// - `c` is a 0-based cell index within `table.rows[r].cells`.
579+
/// - `g0` and `g1` are 0-based grid column indices into `table.grid`.
580+
///
581+
/// If `(r, c)` falls outside the table (e.g. missing row or out-of-range cell), `grid_col`
582+
/// clamps to the available cells, and `span` falls back to 1 via `map_or(1, Cell::span)`
583+
/// with saturating arithmetic so bounds never underflow or panic.
575584
fn cell_grid_span(table: &Table, r: usize, c: usize) -> (usize, usize) {
576585
let g0 = table.grid_col(r, c);
577586
let span = table.rows.get(r).and_then(|row| row.cells.get(c)).map_or(1, Cell::span);
578587
let g1 = g0.saturating_add(span).saturating_sub(1);
579588
(g0, g1)
580589
}
581590

582-
/// Slicing bounds for a table selection between `(ra, ca)` and `(rb, cb)`.
591+
/// Calculate row and grid column slicing bounds for a selection between cells `(ra, ca)` and `(rb, cb)`.
592+
///
593+
/// Coordinate systems:
594+
/// - Input coordinates `(ra, ca)` and `(rb, cb)` are `(row_index, cell_index)` in `table`.
595+
/// - Output `rows` is an inclusive range of row indices `(r_min, r_max)`.
596+
/// - Output `cols` is an inclusive range of grid column indices `(g_min, g_max)`, computed from
597+
/// the union of grid column spans of the two endpoint cells via [`cell_grid_span`].
598+
///
599+
/// This forms the minimal bounding rectangle covering both endpoints, ensuring merged or
600+
/// multi-column spanning cells within the selection endpoints are fully enclosed.
583601
fn table_slice_bounds(table: &Table, ra: usize, ca: usize, rb: usize, cb: usize) -> ((usize, usize), (usize, usize)) {
584602
let g_a = cell_grid_span(table, ra, ca);
585603
let g_b = cell_grid_span(table, rb, cb);
@@ -588,8 +606,20 @@ fn table_slice_bounds(table: &Table, ra: usize, ca: usize, rb: usize, cb: usize)
588606
(rows, cols)
589607
}
590608

591-
/// Trim a table endpoint paragraph at `path` within `c_depth` in `table` before slicing,
592-
/// removing unselected sibling blocks before start or after end in the endpoint cell.
609+
/// Trim a table selection endpoint within `table` before slicing.
610+
///
611+
/// Expected path shape:
612+
/// `path` must identify a block directly inside a table cell at depth `c_depth + 4`:
613+
/// `[container_prefix..., table_idx, row_idx, cell_idx, block_idx]`.
614+
/// If `path.0.len() != c_depth + 4`, the path points elsewhere (e.g. an ancestor container
615+
/// or deeply nested child) and the function returns early without modifying `table`.
616+
///
617+
/// Modes and side effects:
618+
/// - **Start trim** (`end_off == None`): Trims the start paragraph at `b_idx` to `off..len`,
619+
/// and drains any preceding sibling blocks in `0..b_idx` that lie before the selection start.
620+
/// - **End trim** (`end_off == Some(end)`): Trims the end paragraph at `b_idx` to `0..end`,
621+
/// and truncates any trailing sibling blocks after `b_idx` that lie after the selection end.
622+
/// - Non-paragraph blocks (e.g. nested tables or drawings) are left intact without text trimming.
593623
fn trim_table_endpoint(table: &mut Table, path: &Path, c_depth: usize, off: usize, end_off: Option<usize>) {
594624
if path.0.len() != c_depth + 4 {
595625
return;
@@ -1312,6 +1342,14 @@ impl Document {
13121342
}
13131343

13141344
// Find the lowest common ancestor container.
1345+
// Document paths encode container hierarchy in triplets:
1346+
// - Top-level story block: `[block_idx]` (depth 0).
1347+
// - Inside a table cell: `[table_idx, row_idx, cell_idx, block_idx]` (depth 3).
1348+
// - Nested table levels add 3 segments per level: `[..., table, row, cell, block]`.
1349+
// Rounding down `common_len` to a multiple of 3 aligns to the nearest enclosing container boundary
1350+
// (`c_depth`). At this depth, `c_depth + 1` is row index, `c_depth + 2` is cell index, and
1351+
// `c_depth + 3` is block index within the cell. A direct paragraph in a cell therefore has
1352+
// length `c_depth + 4`.
13151353
let common_len = a.path.0.iter().zip(&b.path.0).take_while(|(x, y)| x == y).count();
13161354
let c_depth = (common_len / 3) * 3;
13171355
let c_path = Path(a.path.0.get(..c_depth + 1).map(<[u32]>::to_vec).unwrap_or_default());

β€Žcrates/doc/src/edit/tests.rsβ€Ž

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1134,3 +1134,122 @@ fn copy_range_multi_block_cell_endpoint_trims_siblings() {
11341134
};
11351135
assert_eq!(end_p, "End", "end para trimmed");
11361136
}
1137+
1138+
/// #5906: Copy range between non-corner cells in a 3x3 table copies only the bounded column slice.
1139+
#[test]
1140+
fn copy_range_non_corner_endpoints_inner_cells() {
1141+
let mut d = Document::new();
1142+
let mut t = Table::new(3, 3, 300.0);
1143+
for r in 0..3 {
1144+
for c in 0..3 {
1145+
t.rows[r].cells[c].blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
1146+
}
1147+
}
1148+
d.body = vec![Arc::new(Block::Table(t))];
1149+
// Start at (0, 1) offset 1 ("0C1"), end at (1, 1) offset 3 ("R1C")
1150+
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 1 };
1151+
let b = Pos { story: StoryRef::Body, path: Path(vec![0, 1, 1, 0]), off: 3 };
1152+
let frag = d.copy_range(&a, &b);
1153+
let Block::Table(sliced) = &frag.blocks[0] else { panic!("expected Table") };
1154+
assert_eq!(sliced.rows.len(), 2, "rows 0 and 1 copied");
1155+
assert_eq!(sliced.cols(), 1, "only column 1 copied, corners excluded");
1156+
let p0 = sliced.rows[0].cells[0].blocks.first().and_then(|b| match &**b {
1157+
Block::Para(p) => Some(p.text.as_str()),
1158+
_ => None,
1159+
});
1160+
assert_eq!(p0, Some("0C1"), "cell (0,1) start trimmed");
1161+
let p1 = sliced.rows[1].cells[0].blocks.first().and_then(|b| match &**b {
1162+
Block::Para(p) => Some(p.text.as_str()),
1163+
_ => None,
1164+
});
1165+
assert_eq!(p1, Some("R1C"), "cell (1,1) end trimmed");
1166+
}
1167+
1168+
/// #5906: Copy range from paragraph before table into non-corner cell slices all columns for rows 0..=rb.
1169+
#[test]
1170+
fn copy_range_from_para_before_table_to_non_corner_cell() {
1171+
let mut d = Document::new();
1172+
let mut t = Table::new(3, 3, 300.0);
1173+
for r in 0..3 {
1174+
for c in 0..3 {
1175+
t.rows[r].cells[c].blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
1176+
}
1177+
}
1178+
d.body = vec![Arc::new(Block::Para(Paragraph::with_text("LeadingText", CharProps::default()))), Arc::new(Block::Table(t))];
1179+
let a = Pos { story: StoryRef::Body, path: Path(vec![0]), off: 7 };
1180+
let b = Pos { story: StoryRef::Body, path: Path(vec![1, 1, 1, 0]), off: 3 };
1181+
let frag = d.copy_range(&a, &b);
1182+
assert_eq!(frag.blocks.len(), 2);
1183+
let Block::Para(p) = &frag.blocks[0] else { panic!("expected Para") };
1184+
assert_eq!(p.text.as_str(), "Text");
1185+
let Block::Table(sliced) = &frag.blocks[1] else { panic!("expected Table") };
1186+
assert_eq!(sliced.rows.len(), 2);
1187+
assert_eq!(sliced.cols(), 3);
1188+
assert_eq!(sliced.rows[0].cells.len(), 3, "row 0 retains all 3 cells");
1189+
assert_eq!(sliced.rows[1].cells.len(), 3, "row 1 retains all 3 cells");
1190+
let p_mid = sliced.rows[1].cells[1].blocks.first().and_then(|b| match &**b {
1191+
Block::Para(p) => Some(p.text.as_str()),
1192+
_ => None,
1193+
});
1194+
assert_eq!(p_mid, Some("R1C"), "target cell (1,1) trimmed to offset 3");
1195+
}
1196+
1197+
/// #5906: Copy range with multi-column spans slices exact grid columns and cell texts.
1198+
#[test]
1199+
fn copy_range_spanned_cells_grid_column_slicing() {
1200+
let mut d = Document::new();
1201+
let mut t = Table::new(3, 3, 300.0);
1202+
// Row 0: Cell 0 (span 1, "A0"), Cell 1 (span 2, "A1_span")
1203+
t.rows[0].cells = vec![
1204+
Cell { blocks: vec![para_block(Paragraph::with_text("A0", CharProps::default()))], ..Cell::empty() },
1205+
Cell {
1206+
props: crate::props::CellProps { span: 2, ..Default::default() },
1207+
blocks: vec![para_block(Paragraph::with_text("A1_span", CharProps::default()))],
1208+
..Cell::empty()
1209+
},
1210+
];
1211+
// Row 1: 3 single-span cells
1212+
t.rows[1].cells = vec![
1213+
Cell { blocks: vec![para_block(Paragraph::with_text("B0", CharProps::default()))], ..Cell::empty() },
1214+
Cell { blocks: vec![para_block(Paragraph::with_text("B1", CharProps::default()))], ..Cell::empty() },
1215+
Cell { blocks: vec![para_block(Paragraph::with_text("B2", CharProps::default()))], ..Cell::empty() },
1216+
];
1217+
// Row 2: 3 single-span cells
1218+
t.rows[2].cells = vec![
1219+
Cell { blocks: vec![para_block(Paragraph::with_text("C0", CharProps::default()))], ..Cell::empty() },
1220+
Cell { blocks: vec![para_block(Paragraph::with_text("C1", CharProps::default()))], ..Cell::empty() },
1221+
Cell { blocks: vec![para_block(Paragraph::with_text("C2", CharProps::default()))], ..Cell::empty() },
1222+
];
1223+
d.body = vec![Arc::new(Block::Table(t))];
1224+
1225+
// Select from cell (0, 1) (the 2-column spanned cell covering grid cols 1..=2) to cell (1, 1) (grid col 1)
1226+
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 0 };
1227+
let b = Pos { story: StoryRef::Body, path: Path(vec![0, 1, 1, 0]), off: 2 };
1228+
let frag = d.copy_range(&a, &b);
1229+
let Block::Table(sliced) = &frag.blocks[0] else { panic!("expected Table") };
1230+
1231+
// Sliced table should cover rows 0..=1 and grid columns 1..=2 (width 2 grid columns)
1232+
assert_eq!(sliced.rows.len(), 2);
1233+
assert_eq!(sliced.cols(), 2, "grid columns 1..=2 sliced");
1234+
// Row 0 has the spanned cell (span 2)
1235+
assert_eq!(sliced.rows[0].cells.len(), 1);
1236+
assert_eq!(sliced.rows[0].cells[0].span(), 2);
1237+
let text_0 = match &*sliced.rows[0].cells[0].blocks[0] {
1238+
Block::Para(p) => p.text.as_str(),
1239+
_ => "",
1240+
};
1241+
assert_eq!(text_0, "A1_span");
1242+
1243+
// Row 1 has cells B1 and B2
1244+
assert_eq!(sliced.rows[1].cells.len(), 2);
1245+
let text_1_0 = match &*sliced.rows[1].cells[0].blocks[0] {
1246+
Block::Para(p) => p.text.as_str(),
1247+
_ => "",
1248+
};
1249+
assert_eq!(text_1_0, "B1");
1250+
let text_1_1 = match &*sliced.rows[1].cells[1].blocks[0] {
1251+
Block::Para(p) => p.text.as_str(),
1252+
_ => "",
1253+
};
1254+
assert_eq!(text_1_1, "B2");
1255+
}

β€Žcrates/formats/src/html/builder.rsβ€Ž

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -57,21 +57,16 @@ struct TableB {
5757
}
5858

5959
impl TableB {
60-
/// Commit pending colgroup widths: if childless, push span columns with group width;
61-
/// if child cols lacked explicit widths, backfill with group width.
60+
/// Commit pending colgroup widths: if childless, push span columns with group width.
61+
/// When child `<col>` elements are present, they have already received the group width
62+
/// during `<col>` handling; columns from earlier groups are never backfilled.
6263
fn commit_pending_colgroup(&mut self) {
63-
if let Some((span, group_w, has_child_cols)) = self.pending_colgroup.take() {
64-
if !has_child_cols {
65-
for _ in 0..span {
66-
if self.col_widths.len() < MAX_TABLE_COLS {
67-
self.col_widths.push(group_w);
68-
}
69-
}
70-
} else if let Some(gw) = group_w {
71-
for w in &mut self.col_widths {
72-
if w.is_none() {
73-
*w = Some(gw);
74-
}
64+
if let Some((span, group_w, has_child_cols)) = self.pending_colgroup.take()
65+
&& !has_child_cols
66+
{
67+
for _ in 0..span {
68+
if self.col_widths.len() < MAX_TABLE_COLS {
69+
self.col_widths.push(group_w);
7570
}
7671
}
7772
}
@@ -844,7 +839,15 @@ impl<'r> Builder<'r> {
844839
}
845840
}
846841

847-
/// Finalize an open HTML element, attaching its generated content to the current container.
842+
/// Finalize an open HTML element popped from the stack.
843+
///
844+
/// Side effects:
845+
/// - Flushes any buffered inline text into the current block container.
846+
/// - Sets `pending_page_break` if the element requests page break before or after.
847+
/// - For `Cell`: pops the cell container, attaches generated blocks to the cell, and pushes into the active row.
848+
/// - For `Tr`: commits any pending `<colgroup>` definitions and pushes the completed row into the active table.
849+
/// - For `Table`: commits pending colgroup widths, finalizes table rows with `insert_covered` (bounded to `MAX_ROWS`),
850+
/// resolves explicit column widths from colgroups/cells, and appends the resulting table to the enclosing container.
848851
fn close(&mut self, e: &El) {
849852
if e.page_break_after || e.page_break {
850853
self.pending_page_break = true;
@@ -1004,7 +1007,14 @@ impl<'r> Builder<'r> {
10041007
}
10051008
}
10061009

1007-
/// Handle void or special elements such as `br`, `hr`, `col`, `colgroup`, or `img`.
1010+
/// Process void or special HTML elements (`br`, `hr`, `wbr`, `col`, `colgroup`, `img`).
1011+
///
1012+
/// Side effects:
1013+
/// - `br` / `wbr`: inserts line break or zero-width break into the active paragraph.
1014+
/// - `hr`: inserts a thematic horizontal rule block with borders and spacing into the container.
1015+
/// - `col`: extracts span and explicit CSS width, resolves against active `<colgroup>`, and appends up to `MAX_TABLE_COLS` column widths to the table.
1016+
/// - `colgroup`: commits any previous pending colgroup and buffers new span and width styles until child cols or closing tag arrive.
1017+
/// - `img`: parses dimensions, styles, and data/remote sources, creating an image block or inline image run.
10081018
fn start_special(&mut self, name: &str, attrs: &[(String, String)]) -> bool {
10091019
match name {
10101020
"br" => {
@@ -1138,7 +1148,16 @@ impl<'r> Builder<'r> {
11381148
ElementStyle { fmt, align, preserve, page_break, page_break_after }
11391149
}
11401150

1141-
/// Begin an HTML element, setting up formatting styles, container blocks, or pushing onto the element stack.
1151+
/// Begin an HTML element, pushing it onto the element stack.
1152+
///
1153+
/// Side effects:
1154+
/// - Processes head metadata (`title`, `meta`, `style`) if within `<head>`.
1155+
/// - Flushes inline runs for non-inline elements and computes cascading CSS properties.
1156+
/// - For `Table`: pushes a new `TableB` state tracker with border and column width buffers.
1157+
/// - For `Tr`: commits any pending colgroup widths and initializes a new row buffer.
1158+
/// - For `Cell`: ensures an active row exists, records colspan, rowspan, background shading, borders,
1159+
/// vertical alignment, and Word vertical merge continuation flags, and opens a new block container.
1160+
/// - For other block elements: creates paragraphs, headings, or list item containers.
11421161
pub(super) fn start(&mut self, name: &str, attrs: &[(String, String)], self_close: bool) {
11431162
if self.start_head_metadata(name, attrs) {
11441163
return;

β€Žcrates/formats/src/html/tests.rsβ€Ž

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -778,6 +778,69 @@ fn word_html_vertical_merge_is_preserved() {
778778
assert_eq!(tb.vertical_extent(0, 0), Some((0, 2)));
779779
}
780780

781+
#[test]
782+
fn html_multiple_colgroups_do_not_backfill_earlier_groups() {
783+
// Earlier colgroup with unset column must not be backfilled by later colgroup width.
784+
let html = "<table>\
785+
<colgroup><col></colgroup>\
786+
<colgroup style='width: 200pt'><col style='width: 50pt'></colgroup>\
787+
<tr><td>1</td><td>2</td></tr>\
788+
</table>";
789+
let f = parse(html);
790+
let FBlock::Table(t) = &f.blocks[0] else { panic!() };
791+
assert_eq!(t.widths, [50.0, 50.0], "column 0 was not backfilled by group 2 width of 200pt");
792+
}
793+
794+
#[test]
795+
fn word_html_rowspan_with_explicit_vmerge_continue_not_ragged() {
796+
use wordcraft_doc::props::VMerge;
797+
// Row 0 has both rowspan="2" and mso-yfti-vmerge:restart.
798+
// Row 1 has explicit mso-yfti-vmerge:continue cell.
799+
// insert_covered must not insert a duplicate covered cell in row 1.
800+
let html = "<table>\
801+
<tr><td rowspan='2' style='mso-yfti-vmerge:restart'>Top</td><td>B1</td></tr>\
802+
<tr><td style='mso-yfti-vmerge:continue'>Cont</td><td>B2</td></tr>\
803+
</table>";
804+
let f = parse(html);
805+
let FBlock::Table(t) = &f.blocks[0] else { panic!() };
806+
assert_eq!(t.rows.len(), 2);
807+
assert_eq!(t.rows[0].len(), 2);
808+
assert_eq!(t.rows[1].len(), 2, "second row must have exactly 2 cells, not ragged");
809+
assert!(!t.rows[0][0].covered);
810+
assert!(t.rows[1][0].covered);
811+
812+
let doc = crate::model::to_doc(&f);
813+
let wordcraft_doc::Block::Table(tb) = &*doc.body[0] else { panic!() };
814+
assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart);
815+
assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue);
816+
assert_eq!(tb.rows[1].cells.len(), 2);
817+
assert_eq!(tb.vertical_extent(0, 0), Some((0, 2)));
818+
}
819+
820+
#[test]
821+
fn to_doc_normalises_row_0_continue_cell() {
822+
use wordcraft_doc::props::VMerge;
823+
// Case 1: Row 0 has continue and Row 1 has continue -> Row 0 normalised to Restart.
824+
let html_multi = "<table>\
825+
<tr><td style='mso-yfti-vmerge:continue'>TopCont</td><td>B1</td></tr>\
826+
<tr><td style='mso-yfti-vmerge:continue'>BottomCont</td><td>B2</td></tr>\
827+
</table>";
828+
let f_multi = parse(html_multi);
829+
let doc_multi = crate::model::to_doc(&f_multi);
830+
let wordcraft_doc::Block::Table(tb_multi) = &*doc_multi.body[0] else { panic!() };
831+
assert_eq!(tb_multi.rows[0].cells[0].props.vmerge, VMerge::Restart, "row 0 continue normalised to restart");
832+
assert_eq!(tb_multi.rows[1].cells[0].props.vmerge, VMerge::Continue);
833+
834+
// Case 2: Row 0 has continue but table has only 1 row (or no continuation) -> normalised to None.
835+
let html_single = "<table>\
836+
<tr><td style='mso-yfti-vmerge:continue'>SoloCont</td><td>B1</td></tr>\
837+
</table>";
838+
let f_single = parse(html_single);
839+
let doc_single = crate::model::to_doc(&f_single);
840+
let wordcraft_doc::Block::Table(tb_single) = &*doc_single.body[0] else { panic!() };
841+
assert_eq!(tb_single.rows[0].cells[0].props.vmerge, VMerge::None, "orphaned row 0 continue normalised to none");
842+
}
843+
781844
#[test]
782845
fn cells_take_their_css_borders() {
783846
use wordcraft_doc::props::{Border, BorderStyle};

β€Žcrates/formats/src/model/to_doc.rsβ€Ž

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -888,6 +888,16 @@ impl<'a> Builder<'a> {
888888
}
889889
tb.rows.push(row);
890890
}
891+
let starts: Vec<(usize, usize)> = (0..tb.rows.first().map_or(0, |row| row.cells.len()))
892+
.filter(|&ci| tb.rows.first().and_then(|row| row.cells.get(ci)).is_some_and(|c| c.props.vmerge == VMerge::Continue))
893+
.map(|ci| (ci, tb.grid_col(0, ci)))
894+
.collect();
895+
for (ci, g) in starts {
896+
let more = tb.cell_at_grid(1, g).and_then(|i| tb.rows.get(1)?.cells.get(i)).is_some_and(|c| c.props.vmerge == VMerge::Continue);
897+
if let Some(cell) = tb.rows.first_mut().and_then(|r| r.cells.get_mut(ci)) {
898+
cell.props.vmerge = if more { VMerge::Restart } else { VMerge::None };
899+
}
900+
}
891901
for r in 1..tb.rows.len() {
892902
for ci in 0..tb.rows[r].cells.len() {
893903
if tb.rows[r].cells[ci].props.vmerge == VMerge::Continue {
@@ -900,6 +910,8 @@ impl<'a> Builder<'a> {
900910
if up_cell.props.vmerge == VMerge::None {
901911
up_cell.props.vmerge = VMerge::Restart;
902912
}
913+
} else {
914+
tb.rows[r].cells[ci].props.vmerge = VMerge::None;
903915
}
904916
}
905917
}

β€Žcrates/formats/src/model/types.rsβ€Ž

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1006,6 +1006,12 @@ impl FTable {
10061006
}
10071007
x += cc.colspan.clamp(1, 63) as usize;
10081008
}
1009+
if at < row.len() && x == g && row[at].covered {
1010+
// Row already has an explicit covered cell at this grid column
1011+
// (e.g. from Word HTML `mso-yfti-vmerge:continue`). Avoid adding
1012+
// a duplicate synthetic covered cell which would make the row ragged.
1013+
continue;
1014+
}
10091015
if row.len() < 64 {
10101016
row.insert(at, Cell { colspan: span as u32, covered: true, ..Default::default() });
10111017
}

0 commit comments

Comments
Β (0)