From c0edd96888939f70e02066085281f1d3cd9cd7ca Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Wed, 18 Nov 2026 00:31:10 -0300 Subject: [PATCH] craft-html, craft-flow: preserve table structure, colgroup widths and vertical merges (#1785) (#1802) * craft-html, craft-flow: preserve table structure, colgroup widths and vertical merges (#1785) * craft-html: address CodeRabbit review feedback on vmerge and colgroups (#1785) * craft-html: precompute grid column offsets in table export * craft-html: preserve fully covered rows during table import (#1785) * craft-html: resolve merge conflict artifacts and unclosed delimiter in tests (#1785) * craft-flow, craft-html: validate matching spans on vmerge and preserve leading grid columns (#1785) --- crates/flow/src/from_doc.rs | 5 + crates/flow/src/to_doc.rs | 35 +++ crates/flow/src/types.rs | 18 +- crates/html/src/doc/builder.rs | 142 +++++++++-- crates/html/src/doc/export.rs | 81 ++++++- crates/html/src/doc/tests.rs | 423 +++++++++++++++++++++++++++++++++ 6 files changed, 681 insertions(+), 23 deletions(-) diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index e3e915201..b167779e7 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -1114,6 +1114,9 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa // Word. Only Repeat as header row makes it one then. let header = r.props.header || (ri == 0 && style.is_some() && t.props.look.header_row && t.rows.len() > 1); let mut cells = Vec::new(); + for _ in 0..r.first_grid() { + cells.push(Cell::default()); + } for (ci, c) in r.cells.iter().enumerate() { let styled = if bake { styled_cell(t, style.as_ref(), (ri, ci), ncols) } else { None }; let mut rowspan = 1; @@ -1159,6 +1162,8 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa Some(Box::new(crate::CellPic { img, repeat: p.repeat, align: p.align })) }), width: None, + vmerge_restart: c.props.vmerge == VMerge::Restart, + synthetic_covered: false, }); } rows.push(cells); diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index 0375c448c..faf08bb99 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -907,6 +907,41 @@ impl<'a> Builder<'a> { } tb.rows.push(row); } + let starts: Vec<(usize, usize)> = (0..tb.rows.first().map_or(0, |row| row.cells.len())) + .filter(|&ci| tb.rows.first().and_then(|row| row.cells.get(ci)).is_some_and(|c| c.props.vmerge == VMerge::Continue)) + .map(|ci| (ci, tb.grid_col(0, ci))) + .collect(); + for (ci, g) in starts { + let span = tb.rows.first().map_or(1, |r| r.cells[ci].props.span); + let more = tb + .cell_at_grid(1, g) + .filter(|&i| tb.grid_col(1, i) == g) + .and_then(|i| tb.rows.get(1)?.cells.get(i)) + .is_some_and(|c| c.props.vmerge == VMerge::Continue && c.props.span == span); + if let Some(cell) = tb.rows.first_mut().and_then(|r| r.cells.get_mut(ci)) { + cell.props.vmerge = if more { VMerge::Restart } else { VMerge::None }; + } + } + for r in 1..tb.rows.len() { + for ci in 0..tb.rows[r].cells.len() { + if tb.rows[r].cells[ci].props.vmerge == VMerge::Continue { + let g = tb.grid_col(r, ci); + let span = tb.rows[r].cells[ci].props.span; + let prev_r = r - 1; + if let Some(up_ci) = tb.cell_at_grid(prev_r, g) + && tb.grid_col(prev_r, up_ci) == g + && tb.rows[prev_r].cells[up_ci].props.span == span + { + let up_cell = &mut tb.rows[prev_r].cells[up_ci]; + if up_cell.props.vmerge == VMerge::None { + up_cell.props.vmerge = VMerge::Restart; + } + } else { + tb.rows[r].cells[ci].props.vmerge = VMerge::None; + } + } + } + } // Its markup kept for the writer, by its place among the top's tables. if depth == 0 { if t.kept.is_some() || t.wrap.is_some() { diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index d5abb7537..fcd955a30 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -881,6 +881,10 @@ pub struct Cell { /// The width, points, the source gives a cell spanning one column (HTML): see /// [`FTable::widths_from_cells`]. pub width: Option, + /// Whether the source explicitly started a vertical merge (`mso-yfti-vmerge:restart`). + pub vmerge_restart: bool, + /// Whether this covered placeholder was synthesized by [`FTable::insert_covered`]. + pub synthetic_covered: bool, } /// A cell's background picture: the picture at its own size, how it fills the cell, and where an @@ -907,6 +911,8 @@ impl Default for Cell { direction: Default::default(), picture: None, width: None, + vmerge_restart: false, + synthetic_covered: false, } } } @@ -999,8 +1005,8 @@ impl FTable { let mut g = 0usize; let mut ci = 0usize; while let Some(c) = self.rows.get(r).and_then(|row| row.get(ci)) { - let (span, rs, covered) = (c.colspan.clamp(1, 63) as usize, c.rowspan.clamp(1, 1000) as usize, c.covered); - if rs > 1 && !covered { + let (span, rs, vmerge_restart) = (c.colspan.clamp(1, 63) as usize, c.rowspan.clamp(1, 1000) as usize, c.vmerge_restart); + if rs > 1 { for k in 1..rs { work += 1; if work > MAX_COVERED_WORK { @@ -1017,8 +1023,14 @@ impl FTable { } x += cc.colspan.clamp(1, 63) as usize; } + if at < row.len() && x == g && row[at].covered && (vmerge_restart || row[at].synthetic_covered) { + // Row already has a matching explicit continuation (when this cell had + // `mso-yfti-vmerge:restart`) or a synthetic placeholder from an earlier + // row. Avoid adding a duplicate covered cell which would make the row ragged. + continue; + } if row.len() < 64 { - row.insert(at, Cell { colspan: span as u32, covered: true, ..Default::default() }); + row.insert(at, Cell { colspan: span as u32, covered: true, synthetic_covered: true, ..Default::default() }); } } } diff --git a/crates/html/src/doc/builder.rs b/crates/html/src/doc/builder.rs index 68bb7d8db..b6859523f 100644 --- a/crates/html/src/doc/builder.rs +++ b/crates/html/src/doc/builder.rs @@ -55,6 +55,27 @@ struct TableB { row: Option>, /// The table or one of its cells asks for borders. bordered: bool, + /// Explicit column widths from `` and childless ``. + col_widths: Vec>, + /// Pending ``: `(span, width, has_child_cols)`. + pending_colgroup: Option<(usize, Option, bool)>, +} + +impl TableB { + /// Commit pending colgroup widths: if childless, push span columns with group width. + /// When child `` elements are present, they have already received the group width + /// during `` handling; columns from earlier groups are never backfilled. + fn commit_pending_colgroup(&mut self) { + if let Some((span, group_w, has_child_cols)) = self.pending_colgroup.take() + && !has_child_cols + { + for _ in 0..span { + if self.col_widths.len() < MAX_TABLE_COLS { + self.col_widths.push(group_w); + } + } + } + } } struct ElementStyle { @@ -863,6 +884,15 @@ impl<'r> Builder<'r> { } } + /// Finalize an open HTML element popped from the stack. + /// + /// Side effects: + /// - Flushes any buffered inline text into the current block container. + /// - Sets `pending_page_break` if the element requests page break before or after. + /// - For `Cell`: pops the cell container, attaches generated blocks to the cell, and pushes into the active row. + /// - For `Tr`: commits any pending `` definitions and pushes the completed row into the active table. + /// - For `Table`: commits pending colgroup widths, finalizes table rows with `insert_covered` (bounded to `MAX_ROWS`), + /// resolves explicit column widths from colgroups/cells, and appends the resulting table to the enclosing container. fn close(&mut self, e: &El) { if e.page_break_after || e.page_break { self.pending_page_break = true; @@ -881,26 +911,53 @@ impl<'r> Builder<'r> { } } ElKind::Tr => { - if let Some(t) = self.tables.last_mut() - && let Some(r) = t.row.take() - { - t.rows.push(r); + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + if let Some(r) = t.row.take() { + t.rows.push(r); + } } } ElKind::Table => { if let Some(mut t) = self.tables.pop() { + t.commit_pending_colgroup(); if let Some(r) = t.row.take() { t.rows.push(r); } let borderless = !t.bordered; // Keep at most MAX_ROWS rows (the model drops the rest anyway): bounds the // O(rows × rowspan) work of `insert_covered` on a table of millions of ``. - let rows: Vec<_> = t.rows.into_iter().filter(|r| !r.is_empty()).take(craft_wordmodel::table::MAX_ROWS).collect(); + let rows: Vec<_> = t.rows.into_iter().take(craft_wordmodel::table::MAX_ROWS).collect(); let mut ft = FTable { rows, widths: Vec::new(), borderless, extra: None, kept: None, wrap: None }; + let col_widths = &t.col_widths; if !ft.rows.is_empty() { ft.insert_covered(); - // Columns keep the widths their cells give when every column has one. - if ft.cols() <= MAX_TABLE_COLS { + ft.rows.retain(|r| !r.is_empty()); + } + if !ft.rows.is_empty() { + if !col_widths.is_empty() && ft.cols() <= MAX_TABLE_COLS { + let mut widths = vec![None; ft.cols()]; + for (i, &cw) in col_widths.iter().take(ft.cols()).enumerate() { + if let Some(w) = cw { + widths[i] = Some(w); + } + } + for row in &ft.rows { + let mut g = 0; + for c in row { + if let (Some(w), Some(slot)) = (c.width, widths.get_mut(g)) { + slot.get_or_insert(w); + } + g += c.colspan.clamp(1, 63) as usize; + } + } + if widths.iter().any(Option::is_some) { + let known_sum: f32 = widths.iter().filter_map(|w| *w).sum(); + let known_count = widths.iter().filter(|w| w.is_some()).count(); + let avg = if known_count > 0 { known_sum / known_count as f32 } else { 72.0 }; + ft.widths = widths.into_iter().map(|w| w.unwrap_or(avg)).collect(); + } + } else if ft.cols() <= MAX_TABLE_COLS { ft.widths_from_cells(); } self.container().push(FBlock::Table(ft)); @@ -1001,6 +1058,14 @@ impl<'r> Builder<'r> { } } + /// Process void or special HTML elements (`br`, `hr`, `wbr`, `col`, `colgroup`, `img`). + /// + /// Side effects: + /// - `br` / `wbr`: inserts line break or zero-width break into the active paragraph. + /// - `hr`: inserts a thematic horizontal rule block with borders and spacing into the container. + /// - `col`: extracts span and explicit CSS width, resolves against active ``, and appends up to `MAX_TABLE_COLS` column widths to the table. + /// - `colgroup`: commits any previous pending colgroup and buffers new span and width styles until child cols or closing tag arrive. + /// - `img`: parses dimensions, styles, and data/remote sources, creating an image block or inline image run. fn start_special(&mut self, name: &str, attrs: &[(String, String)]) -> bool { match name { "br" => { @@ -1020,6 +1085,34 @@ impl<'r> Builder<'r> { let fmt = self.fmt(); self.start_para().push_text("\u{200B}", &fmt); } + "col" => { + let css = self.css_of(name, attrs); + let span = attr(attrs, "span").and_then(|v| v.trim().parse::().ok()).unwrap_or(1).clamp(1, MAX_TABLE_COLS); + let w = cell_width(&css, attrs); + if let Some(t) = self.tables.last_mut() { + let group_w = if let Some((_, group_w, has_child_cols)) = &mut t.pending_colgroup { + *has_child_cols = true; + *group_w + } else { + None + }; + let effective_w = w.or(group_w); + for _ in 0..span { + if t.col_widths.len() < MAX_TABLE_COLS { + t.col_widths.push(effective_w); + } + } + } + } + "colgroup" => { + let css = self.css_of(name, attrs); + let span = attr(attrs, "span").and_then(|v| v.trim().parse::().ok()).unwrap_or(1).clamp(1, MAX_TABLE_COLS); + let w = cell_width(&css, attrs); + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + t.pending_colgroup = Some((span, w, false)); + } + } "img" => { let alt = attr(attrs, "alt").unwrap_or("").to_string(); let dim = |key: &str| attr(attrs, key).and_then(|v| v.trim().trim_end_matches("px").trim().parse::().ok()).map(|p| p * 0.75); @@ -1164,12 +1257,20 @@ impl<'r> Builder<'r> { let css = self.css_of(name, attrs); let ElementStyle { mut fmt, block_background, align, preserve, page_break, page_break_after } = self.element_style(name, attrs, kind, &css); match kind { - ElKind::Table => self.tables.push(TableB { rows: Vec::new(), row: None, bordered: declares_border(attrs, &css, true) }), + ElKind::Table => self.tables.push(TableB { + rows: Vec::new(), + row: None, + bordered: declares_border(attrs, &css, true), + col_widths: Vec::new(), + pending_colgroup: None, + }), ElKind::Tr => { - if let Some(t) = self.tables.last_mut() - && let Some(r) = t.row.take() - { - t.rows.push(r); + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + if let Some(r) = t.row.take() { + t.rows.push(r); + } + t.row = Some(Vec::new()); } } ElKind::Cell => { @@ -1216,11 +1317,16 @@ impl<'r> Builder<'r> { _ => {} } } + // The last declaration wins, as in the cascade. + let mso_vmerge = decls(&css).filter(|(k, _)| k == "mso-yfti-vmerge").last().map(|(_, v)| v.trim().to_ascii_lowercase()); + let is_mso_vmerge_continue = mso_vmerge.as_deref() == Some("continue"); + let is_mso_vmerge_restart = mso_vmerge.as_deref() == Some("restart"); + let rowspan = attr(attrs, "rowspan").and_then(|v| v.trim().parse::().ok()).map(|v| v.clamp(1, 1000)).unwrap_or(1); self.cells.push(Cell { blocks: Vec::new(), colspan, - rowspan: attr(attrs, "rowspan").and_then(|v| v.trim().parse::().ok()).map(|v| v.clamp(1, 1000)).unwrap_or(1), - covered: false, + rowspan, + covered: is_mso_vmerge_continue, header: name == "th", shading, borders: cell_borders(&css), @@ -1229,6 +1335,8 @@ impl<'r> Builder<'r> { direction: Default::default(), picture: None, width: if colspan == 1 { cell_width(&css, attrs) } else { None }, + vmerge_restart: is_mso_vmerge_restart, + synthetic_covered: false, }); fmt.background = None; self.containers.push(Vec::new()); @@ -1261,6 +1369,12 @@ impl<'r> Builder<'r> { } return; } + if name == "colgroup" { + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + } + return; + } let crosses = matches!(name, "table"); let target = if matches!(name, "td" | "th") { self.find_open(|e| e.kind == ElKind::Cell, |e| e.kind == ElKind::Table) diff --git a/crates/html/src/doc/export.rs b/crates/html/src/doc/export.rs index 9fb861d85..52f7f50f0 100644 --- a/crates/html/src/doc/export.rs +++ b/crates/html/src/doc/export.rs @@ -263,21 +263,87 @@ fn para_html(p: &Para) -> String { } } +/// Render an HTML table element, emitting `` column widths and cell attributes. fn table_html(t: &FTable, out: &mut String, depth: usize) { out.push_str("\n"); - for row in &t.rows { - out.push_str(""); - for c in row { - if c.covered { + if !t.widths.is_empty() { + out.push_str("\n"); + for w in &t.widths { + out.push_str(&format!("\n")); + } + out.push_str("\n"); + } + let nrows = t.rows.len(); + let grid_cols: Vec> = t + .rows + .iter() + .map(|row| { + let mut x = 0usize; + row.iter() + .map(|c| { + let start = x; + x = x.saturating_add(c.colspan.clamp(1, 63) as usize); + start + }) + .collect() + }) + .collect(); + let cell_at_grid = |r: usize, target_g: usize| -> Option { grid_cols.get(r)?.binary_search(&target_g).ok() }; + let grid_col = |r: usize, ci: usize| -> usize { grid_cols.get(r).and_then(|row| row.get(ci)).copied().unwrap_or(0) }; + + let mut is_covered: Vec> = t.rows.iter().map(|r| vec![false; r.len()]).collect(); + let mut rowspans: Vec> = t.rows.iter().map(|r| r.iter().map(|c| c.rowspan.clamp(1, 1000)).collect()).collect(); + + for r in 0..nrows { + let row_len = t.rows.get(r).map_or(0, |row| row.len()); + for ci in 0..row_len { + if is_covered.get(r).and_then(|row| row.get(ci)).copied().unwrap_or(false) { continue; } + let Some(c) = t.rows.get(r).and_then(|row| row.get(ci)) else { continue }; + let g = grid_col(r, ci); + let span = c.colspan.clamp(1, 63) as usize; + let mut extent = 1u32; + for down_r in (r + 1)..nrows { + let Some(down_ci) = cell_at_grid(down_r, g) else { break }; + let Some(down_c) = t.rows.get(down_r).and_then(|row| row.get(down_ci)) else { break }; + let down_covered = is_covered.get(down_r).and_then(|row| row.get(down_ci)).copied().unwrap_or(false); + if grid_col(down_r, down_ci) == g + && down_c.colspan.clamp(1, 63) as usize == span + && down_c.covered + && !down_c.vmerge_restart + && !down_covered + { + if let Some(down_row) = is_covered.get_mut(down_r) + && let Some(slot) = down_row.get_mut(down_ci) + { + *slot = true; + } + extent = extent.saturating_add(1); + } else { + break; + } + } + if let Some(slot) = rowspans.get_mut(r).and_then(|row| row.get_mut(ci)) { + *slot = (*slot).max(extent); + } + } + } + + for (ri, row) in t.rows.iter().enumerate() { + out.push_str(""); + for (ci, c) in row.iter().enumerate() { + if is_covered.get(ri).and_then(|r| r.get(ci)).copied().unwrap_or(false) { + continue; + } + let rowspan = rowspans.get(ri).and_then(|r| r.get(ci)).copied().unwrap_or(c.rowspan.clamp(1, 1000)); let tag = if c.header { "th" } else { "td" }; let mut attrs = String::new(); if c.colspan > 1 { attrs.push_str(&format!(" colspan=\"{}\"", c.colspan)); } - if c.rowspan > 1 { - attrs.push_str(&format!(" rowspan=\"{}\"", c.rowspan)); + if rowspan > 1 { + attrs.push_str(&format!(" rowspan=\"{}\"", rowspan)); } let v_css = match c.valign { Some(VAlign::Center) => "vertical-align:middle", @@ -288,6 +354,9 @@ fn table_html(t: &FTable, out: &mut String, depth: usize) { if !t.borderless { css.insert(0, "border:1px solid #999".to_string()); } + if let Some(w) = c.width { + css.push(format!("width:{w:.2}pt")); + } if let Some(s) = c.shading { css.push(format!("background-color:#{}", s.hex())); } diff --git a/crates/html/src/doc/tests.rs b/crates/html/src/doc/tests.rs index c0b00084b..6c4e5fe8e 100644 --- a/crates/html/src/doc/tests.rs +++ b/crates/html/src/doc/tests.rs @@ -717,6 +717,195 @@ fn cells_give_their_columns_widths() { assert_eq!(t.widths, [75.0, 150.0]); } +#[test] +fn col_elements_give_table_column_widths() { + let f = parse("
AB
"); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.widths, [75.0, 150.0]); + + // col with span + let f2 = parse( + "
123
", + ); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert_eq!(t2.widths, [72.0, 72.0, 144.0]); + + // Childless colgroup defines widths across declared span + let f3 = parse("
12
"); + let FBlock::Table(t3) = &f3.blocks[0] else { panic!() }; + assert_eq!(t3.widths, [75.0, 75.0]); + + // Child col elements override colgroup widths + let f4 = parse("
1
"); + let FBlock::Table(t4) = &f4.blocks[0] else { panic!() }; + assert_eq!(t4.widths, [150.0]); + + // Mixed childless colgroup and colgroup with child col elements + let f5 = parse( + "
123
", + ); + let FBlock::Table(t5) = &f5.blocks[0] else { panic!() }; + assert_eq!(t5.widths, [75.0, 200.0, 300.0]); + + // Child col elements inherit parent colgroup width when unset + let f6 = parse("
12
"); + let FBlock::Table(t6) = &f6.blocks[0] else { panic!() }; + assert_eq!(t6.widths, [90.0, 90.0]); + + // Child col elements without width inherit group width while explicit child width takes precedence + let f7 = parse("
12
"); + let FBlock::Table(t7) = &f7.blocks[0] else { panic!() }; + assert_eq!(t7.widths, [150.0, 90.0]); + + // Partial explicit col widths fall back to average for unset columns + let f8 = parse("
12
"); + let FBlock::Table(t8) = &f8.blocks[0] else { panic!() }; + assert_eq!(t8.widths, [100.0, 100.0]); + + // Export includes colgroup + let doc = model::to_doc(&f); + let html = export(&doc); + assert!(html.contains(""), "html export includes colgroup: {html}"); + assert!(html.contains(""), "{html}"); + assert!(html.contains(""), "{html}"); +} + +#[test] +fn word_html_vertical_merge_is_preserved() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ +
TopB1
ContB2
"; + let f = parse(html); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[0].len(), 2); + assert_eq!(t.rows[1].len(), 2, "second row must have exactly 2 cells, no duplicate synthetic cell"); + assert!(!t.rows[0][0].covered); + assert!(t.rows[1][0].covered); + + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[1].cells.len(), 2, "table model second row has exactly 2 cells"); + assert_eq!(tb.vertical_extent(0, 0), Some((0, 2))); +} + +#[test] +fn html_multiple_colgroups_do_not_backfill_earlier_groups() { + // Earlier colgroup with unset column must not be backfilled by later colgroup width. + let html = "\ + \ + \ + \ +
12
"; + let f = parse(html); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.widths, [50.0, 50.0], "column 0 was not backfilled by group 2 width of 200pt"); +} + +#[test] +fn word_html_rowspan_with_explicit_vmerge_continue_no_duplicate_cell() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ +
AB1
A_contB2
"; + let f = parse(html); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[0].len(), 2); + assert_eq!(t.rows[1].len(), 2, "second row must have exactly 2 cells, not ragged"); + assert!(!t.rows[0][0].covered); + assert!(t.rows[1][0].covered); + + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[1].cells.len(), 2); + assert_eq!(tb.vertical_extent(0, 0), Some((0, 2))); +} + +#[test] +fn to_doc_normalises_row_0_continue_cell() { + use craft_wordmodel::props::VMerge; + // Case 1: Row 0 has continue and Row 1 has continue -> Row 0 normalised to Restart. + let html_multi = "\ + \ + \ +
TopContB1
BottomContB2
"; + let f_multi = parse(html_multi); + let doc_multi = model::to_doc(&f_multi); + let craft_wordmodel::Block::Table(tb_multi) = &*doc_multi.body[0] else { panic!() }; + assert_eq!(tb_multi.rows[0].cells[0].props.vmerge, VMerge::Restart, "row 0 continue normalised to restart"); + assert_eq!(tb_multi.rows[1].cells[0].props.vmerge, VMerge::Continue); + + // Case 2: Row 0 has continue but table has only 1 row (or no continuation) -> normalised to None. + let html_single = "\ + \ +
SoloContB1
"; + let f_single = parse(html_single); + let doc_single = model::to_doc(&f_single); + let craft_wordmodel::Block::Table(tb_single) = &*doc_single.body[0] else { panic!() }; + assert_eq!(tb_single.rows[0].cells[0].props.vmerge, VMerge::None, "orphaned row 0 continue normalised to none"); + + // Case 3: Row 0 col 1 has continue, Row 1 has a spanning continue starting at col 0 -> col 1 normalised to None. + let html_span = "\ + \ + \ +
A0B0
SpanCont
"; + let f_span = parse(html_span); + let doc_span = model::to_doc(&f_span); + let craft_wordmodel::Block::Table(tb_span) = &*doc_span.body[0] else { panic!() }; + assert_eq!(tb_span.rows[0].cells[1].props.vmerge, VMerge::None, "unaligned spanning continuation in row 1 must not mark row 0 cell as restart"); +} + +/// #1785: A covered continuation cell with `rowspan > 1` expands into the following row when +/// no restart cell above spans it. +#[test] +fn covered_continuation_with_rowspan_expands_into_next_row() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ + \ +
TopB0
MidB1
B2
"; + let f = parse(html); + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows.len(), 3); + assert_eq!(tb.rows[2].cells.len(), 2, "row 2 should have placeholder + B2"); + assert_eq!(tb.rows[2].cells[0].props.vmerge, VMerge::Continue); +} + +/// #1785: A plain `rowspan=2` cell `A` in col 0 followed by `B` (`vmerge:restart`) and `D` +/// must still insert a placeholder for `A` in row 1 even when `B`'s explicit `vmerge:continue` +/// is the first `` in row 1. +#[test] +fn rowspan_before_explicit_vmerge_continue_keeps_grid_columns() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ +
ABD
B_contD1
"; + let f = parse(html); + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows.len(), 2); + assert_eq!(tb.rows[0].cells.len(), 3); + assert_eq!(tb.rows[1].cells.len(), 3, "row 1 should have placeholder for A, B_cont, and D1"); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[1].cells[1].props.vmerge, VMerge::Continue); + let craft_wordmodel::Block::Para(p1) = &*tb.rows[1].cells[1].blocks[0] else { panic!() }; + assert_eq!(p1.text, "B_cont"); + assert_eq!(tb.rows[1].cells[2].props.vmerge, VMerge::None); + let craft_wordmodel::Block::Para(p2) = &*tb.rows[1].cells[2].blocks[0] else { panic!() }; + assert_eq!(p2.text, "D1"); +} + #[test] fn cells_take_their_css_borders() { use craft_wordmodel::props::{Border, BorderStyle}; @@ -768,6 +957,240 @@ fn hostile_style_sheets_never_panic() { } } +#[test] +fn conflicting_mso_vmerge_declarations_last_wins() { + let html_restart_wins = "
A
"; + let f1 = parse(html_restart_wins); + let FBlock::Table(t1) = &f1.blocks[0] else { panic!() }; + assert!(t1.rows[0][0].vmerge_restart); + assert!(!t1.rows[0][0].covered); + + let html_continue_wins = "
B
"; + let f2 = parse(html_continue_wins); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert!(!t2.rows[0][0].vmerge_restart); + assert!(t2.rows[0][0].covered); +} + +#[test] +fn export_flow_derives_rowspan_for_vmerge_continuations() { + let html = "\ + \ + \ +
TopB1
ContB2
"; + let f = parse(html); + let exported = export_flow(&f, "en"); + assert!(exported.contains(""), "covered continuation cell should not be emitted: {exported}"); + assert!(exported.contains(">B1"), "{exported}"); + assert!(exported.contains(">B2"), "{exported}"); +} + +#[test] +fn export_flow_preserves_orphan_covered_continuation_content() { + let html = "\ + \ + \ +
Orphan0B0
A1B1
"; + let f = parse(html); + let exported = export_flow(&f, "en"); + assert!(exported.contains("Orphan0"), "orphan continuation content in row 0 must be preserved: {exported}"); +} + +#[test] +fn html_roundtrip_preserves_colgroups_widths_and_vmerge() { + use craft_wordmodel::props::VMerge; + + let html = "\ + \ + \ + \ + \ +
MergeAB1
MergeA_contB2
"; + + let f1 = parse(html); + let FBlock::Table(t1) = &f1.blocks[0] else { panic!() }; + assert_eq!(t1.widths, [80.0, 120.0]); + assert_eq!(t1.rows.len(), 2); + assert_eq!(t1.rows[0].len(), 2); + assert_eq!(t1.rows[1].len(), 2); + assert!(!t1.rows[0][0].covered); + assert!(t1.rows[0][0].vmerge_restart); + assert!(t1.rows[1][0].covered); + + let doc1 = model::to_doc(&f1); + let craft_wordmodel::Block::Table(tb1) = &*doc1.body[0] else { panic!() }; + assert_eq!(tb1.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb1.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb1.vertical_extent(0, 0), Some((0, 2))); + + // Export to HTML via export() + let exported = export(&doc1); + assert!(exported.contains(""), "exported HTML must contain colgroup: {exported}"); + assert!(exported.contains("width:80.00pt"), "{exported}"); + assert!(exported.contains("width:120.00pt"), "{exported}"); + assert!(exported.contains("rowspan=\"2\""), "exported HTML must emit rowspan=\"2\": {exported}"); + + // Parse the exported HTML again + let f2 = parse(&exported); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert_eq!(t2.widths, t1.widths, "column widths must match"); + assert_eq!(t2.rows.len(), t1.rows.len(), "row counts must match"); + assert_eq!(t2.rows[0].len(), t1.rows[0].len(), "row 0 cell count must match"); + assert_eq!(t2.rows[1].len(), t1.rows[1].len(), "row 1 cell count must match"); + assert_eq!(t2.rows[0][0].covered, t1.rows[0][0].covered, "row 0 cell 0 covered flag must match"); + assert_eq!(t2.rows[1][0].covered, t1.rows[1][0].covered, "row 1 cell 0 covered flag must match"); + + let doc2 = model::to_doc(&f2); + let craft_wordmodel::Block::Table(tb2) = &*doc2.body[0] else { panic!() }; + assert_eq!(tb2.rows[0].cells[0].props.vmerge, tb1.rows[0].cells[0].props.vmerge, "vmerge restart matches"); + assert_eq!(tb2.rows[1].cells[0].props.vmerge, tb1.rows[1].cells[0].props.vmerge, "vmerge continue matches"); + assert_eq!(tb2.vertical_extent(0, 0), tb1.vertical_extent(0, 0), "vertical merge extent matches"); +} + +fn assert_single_col_vmerge_table(tb: &craft_wordmodel::Table) { + use craft_wordmodel::props::VMerge; + assert_eq!(tb.rows.len(), 3, "table must have 3 rows"); + assert_eq!(tb.grid.len(), 1, "table must have 1 column"); + assert_eq!(tb.rows[0].cells.len(), 1); + assert_eq!(tb.rows[1].cells.len(), 1); + assert_eq!(tb.rows[2].cells.len(), 1); + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[2].cells[0].props.vmerge, VMerge::None); + assert_eq!(tb.vertical_extent(0, 0), Some((0, 2))); + assert_eq!(tb.grid_col(2, 0), 0, "Bottom cell must be at grid column 0"); + let bottom_text = match &*tb.rows[2].cells[0].blocks[0] { + craft_wordmodel::Block::Para(p) => &p.text, + _ => panic!("expected paragraph in Bottom cell"), + }; + assert_eq!(bottom_text, "Bottom", "Bottom must be at row 2, cell 0"); +} + +#[test] +fn html_roundtrip_preserves_fully_covered_row_and_single_column_table() { + // A one-column table with a Word vertical merge across the first two rows, + // followed by an ordinary "Bottom" cell in row three. + let html = "\ + \ + \ + \ +
Top
Cont
Bottom
"; + + let f1 = parse(html); + let FBlock::Table(t1) = &f1.blocks[0] else { panic!() }; + assert_eq!(t1.rows.len(), 3, "initial import must have 3 rows"); + assert_eq!(t1.cols(), 1, "initial import must have 1 column"); + assert_eq!(t1.rows[0].len(), 1); + assert_eq!(t1.rows[1].len(), 1); + assert_eq!(t1.rows[2].len(), 1); + assert!(!t1.rows[0][0].covered); + assert!(t1.rows[0][0].vmerge_restart); + assert!(t1.rows[1][0].covered); + assert!(!t1.rows[2][0].covered); + + let doc1 = model::to_doc(&f1); + let craft_wordmodel::Block::Table(tb1) = &*doc1.body[0] else { panic!() }; + assert_single_col_vmerge_table(tb1); + + // Export to HTML via export() + let exported = export(&doc1); + assert!(exported.contains("rowspan=\"2\""), "exported HTML must emit rowspan=\"2\": {exported}"); + assert!(exported.contains(""), "covered row with no visible cells must emit empty tr: {exported}"); + assert!(exported.contains("Bottom"), "exported HTML must contain Bottom: {exported}"); + + // Parse the exported HTML again + let f2 = parse(&exported); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert_eq!(t2.rows.len(), 3, "round-trip Flow must keep 3 rows"); + assert_eq!(t2.cols(), 1, "round-trip Flow must keep 1 column"); + assert_eq!(t2.rows[0].len(), 1, "row 0 has 1 cell"); + assert_eq!(t2.rows[1].len(), 1, "row 1 (fully covered row) has 1 cell"); + assert_eq!(t2.rows[2].len(), 1, "row 2 has 1 cell"); + assert!(!t2.rows[0][0].covered); + assert!(t2.rows[1][0].covered, "row 1 cell must be covered placeholder"); + assert!(!t2.rows[2][0].covered, "row 2 cell (Bottom) must not be covered"); + + // Convert round-tripped flow to document model + let doc2 = model::to_doc(&f2); + let craft_wordmodel::Block::Table(tb2) = &*doc2.body[0] else { panic!() }; + assert_single_col_vmerge_table(tb2); +} + +#[test] +fn vmerge_validation_requires_matching_spans() { + use craft_wordmodel::props::VMerge; + + // 1. Later-row check: row 0 has colspan=2, row 1 has continuation with colspan=1. + // Mismatched spans must clear continuation to None and NOT promote row 0 cell to Restart. + let ft_mismatched = FTable { + rows: vec![ + vec![Cell { colspan: 2, ..Cell::default() }], + vec![Cell { colspan: 1, covered: true, ..Cell::default() }, Cell { colspan: 1, ..Cell::default() }], + ], + widths: vec![50.0, 50.0], + ..Default::default() + }; + let doc = model::to_doc(&Flow { blocks: vec![FBlock::Table(ft_mismatched)], ..Default::default() }); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::None, "mismatched span must not promote to Restart"); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::None, "mismatched span must clear Continue to None"); + + // 2. First-row check: row 0 has continuation with colspan=2, row 1 has continuation with colspan=1. + // Mismatched spans must clear row 0 continuation to None, not promote to Restart. + let ft_row0_mismatched = FTable { + rows: vec![ + vec![Cell { colspan: 2, covered: true, ..Cell::default() }], + vec![Cell { colspan: 1, covered: true, ..Cell::default() }, Cell { colspan: 1, ..Cell::default() }], + ], + widths: vec![50.0, 50.0], + ..Default::default() + }; + let doc0 = model::to_doc(&Flow { blocks: vec![FBlock::Table(ft_row0_mismatched)], ..Default::default() }); + let craft_wordmodel::Block::Table(tb0) = &*doc0.body[0] else { panic!() }; + assert_eq!(tb0.rows[0].cells[0].props.vmerge, VMerge::None, "mismatched span in row 0 must clear to None"); + assert_eq!(tb0.rows[1].cells[0].props.vmerge, VMerge::None, "mismatched span in row 1 must clear to None"); + + // 3. Matching spans: row 0 has colspan=2, row 1 has continuation with colspan=2. + // Matching spans must promote row 0 to Restart and keep row 1 as Continue. + let ft_matching = FTable { + rows: vec![vec![Cell { colspan: 2, ..Cell::default() }], vec![Cell { colspan: 2, covered: true, ..Cell::default() }]], + widths: vec![50.0, 50.0], + ..Default::default() + }; + let doc_m = model::to_doc(&Flow { blocks: vec![FBlock::Table(ft_matching)], ..Default::default() }); + let craft_wordmodel::Block::Table(tb_m) = &*doc_m.body[0] else { panic!() }; + assert_eq!(tb_m.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb_m.rows[1].cells[0].props.vmerge, VMerge::Continue); +} + +#[test] +fn export_table_preserves_first_grid_column_alignment() { + let mut doc = craft_wordmodel::Document::default(); + let mut table = craft_wordmodel::Table::new(2, 3, 240.0); + table.grid = vec![40.0, 80.0, 120.0]; + table.rows[0].cells = vec![craft_wordmodel::Cell::with_text("A"), craft_wordmodel::Cell::with_text("B"), craft_wordmodel::Cell::with_text("C")]; + table.rows[1].props.grid_before = 1; + table.rows[1].cells = vec![craft_wordmodel::Cell::with_text("D"), craft_wordmodel::Cell::with_text("E")]; + doc.body = vec![std::sync::Arc::new(craft_wordmodel::Block::Table(table))]; + + // Flow representation should preserve the leading grid position + let flow = model::from_doc(&doc); + let FBlock::Table(ft) = &flow.blocks[0] else { panic!() }; + assert_eq!(ft.rows.len(), 2); + assert_eq!(ft.rows[0].len(), 3); + assert_eq!(ft.rows[1].len(), 3, "row 1 must have 3 cells (1 leading placeholder + 2 data cells)"); + assert_eq!(ft.widths, vec![40.0, 80.0, 120.0]); + + // HTML export should emit 3 colgroup cols and preserve cell alignment + let html = export(&doc); + assert!(html.contains(""), "must contain col 0 width: {html}"); + assert!(html.contains(""), "must contain col 1 width: {html}"); + assert!(html.contains(""), "must contain col 2 width: {html}"); + assert!(html.contains(">D"), "must contain cell D: {html}"); + assert!(html.contains(">E"), "must contain cell E: {html}"); +} + /// Ensure container elements (such as `div` and `p`) with background colors do not leak /// character shading onto their child text runs (#1786). #[test]