craft-flow: narrow table columns keep their width on import

Moves the import part of storytold/wordcraft#4964 into craft-flow, where
WordCraft's RTF and ODT import now builds its tables (#778).

Import raised every column under 6 pt to 6 pt, so a form with many narrow
columns came out wider than its source. Columns over 1 pt now keep the
width the file gives; one of a point or less, none or not a number still
gives the table equal columns, so nothing below a point, negative or NaN
reaches layout.

craft-rtf merged grid columns under 6 pt that no row needed, because import
would widen them. With import keeping them, that merge only moved cell
edges, so it goes: grid columns merge only while there are over 63 or one
is a point or less.

Stacked on the craft-rtf column grid change.
This commit is contained in:
tsw2k committed 2026-11-16 11:40:14 +00:00
1 parent 69d26616e0
commit fe68ce8c51
4 files changed
+69 -18

No files matched your search

+2 -1
View File
@@ -841,7 +841,8 @@ impl<'a> Builder<'a> {
tb.props.style = None;
}
if t.widths.len() == cols && t.widths.iter().all(|w| w.is_finite() && *w > 1.0) {
tb.grid = t.widths.iter().map(|w| w.clamp(6.0, 1584.0)).collect();
// Narrow columns stay as they are: raising them would widen the table past its source.
tb.grid = t.widths.iter().map(|w| w.min(1584.0)).collect();
}
tb.rows.clear();
if let Some(x) = &t.extra {
+35
View File
@@ -442,6 +442,41 @@ fn table_column_widths_survive_a_round_trip() {
assert_eq!(grid(&back), widths);
}
#[test]
fn narrow_table_columns_keep_their_width() {
// Columns of a few points stay as the file gives them, so the table stays as wide as its source.
let content = format!(
r##"<office:document-content {NS_T}><office:automatic-styles><style:style style:name="Table1.A" style:family="table-column"><style:table-column-properties style:column-width="3pt"/></style:style><style:style style:name="Table1.B" style:family="table-column"><style:table-column-properties style:column-width="100pt"/></style:style></office:automatic-styles><office:body><office:text><table:table><table:table-column table:style-name="Table1.A"/><table:table-column table:style-name="Table1.B"/><table:table-row><table:table-cell><text:p>A</text:p></table:table-cell><table:table-cell><text:p>B</text:p></table:table-cell></table:table-row></table:table></office:text></office:body></office:document-content>"##
);
let doc = import(&package(&content, None)).unwrap();
let grid_of = |doc: &craft_wordmodel::Document| {
doc.body.iter().find_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t.grid.clone()) } else { None })
};
assert_eq!(grid_of(&doc), Some(vec![3.0, 100.0]));
// Saved and opened again, the narrow column is still the file's width.
let back = import(&export(&doc).unwrap()).unwrap();
let grid = grid_of(&back).unwrap();
assert_eq!(grid.len(), 2, "{grid:?}");
assert!((grid[0] - 3.0).abs() < 0.01 && (grid[1] - 100.0).abs() < 0.01, "{grid:?}");
}
#[test]
fn table_columns_of_a_point_or_less_give_equal_columns() {
// A column of a point or less, nothing or NaN (a damaged or hostile file) is no width to
// lay out: the whole grid falls back to equal columns, and nothing reaches layout below a
// point, negative or not a number.
for bad in ["1pt", "0.5pt", "0pt", "-3pt", "NaNpt"] {
let content = format!(
r##"<office:document-content {NS_T}><office:automatic-styles><style:style style:name="Table1.A" style:family="table-column"><style:table-column-properties style:column-width="{bad}"/></style:style><style:style style:name="Table1.B" style:family="table-column"><style:table-column-properties style:column-width="100pt"/></style:style></office:automatic-styles><office:body><office:text><table:table><table:table-column table:style-name="Table1.A"/><table:table-column table:style-name="Table1.B"/><table:table-row><table:table-cell><text:p>A</text:p></table:table-cell><table:table-cell><text:p>B</text:p></table:table-cell></table:table-row></table:table></office:text></office:body></office:document-content>"##
);
let doc = import(&package(&content, None)).unwrap();
let grid = doc.body.iter().find_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t.grid.clone()) } else { None }).unwrap();
assert_eq!(grid.len(), 2, "{bad}: {grid:?}");
assert!(grid.iter().all(|w| w.is_finite() && *w > 1.0), "{bad}: {grid:?}");
assert_eq!(grid[0], grid[1], "{bad}: equal columns, {grid:?}");
}
}
#[test]
fn table_without_column_widths_keeps_the_equal_split() {
let content = format!(
+8 -13
View File
@@ -267,10 +267,6 @@ fn finalize(mut r: Reader) -> Parsed {
/// Most grid columns a table gets (the document model's own cap).
const MAX_GRID_COLS: usize = 63;
/// Grid columns under this width, in twips (6 pt), merge while the rows leave room: import widens
/// any narrower column to 6 pt, which grows the table, and files exported from spreadsheets put
/// edges a few twips apart.
const MIN_GRID_GAP: i64 = 120;
/// Grid columns of this width or less, in twips (1 pt), always merge: the document model refuses
/// them, and would then give the table equal columns.
const NO_GRID_GAP: i64 = 20;
@@ -282,9 +278,9 @@ const NO_GRID_GAP: i64 = 20;
///
/// One odd row never costs the whole table its grid (a form exported from a spreadsheet, with
/// many narrow columns, otherwise had its wide title squeezed into one of four equal columns):
/// - Over [`MAX_GRID_COLS`] edges, or edges closer than [`MIN_GRID_GAP`], merge, leaving a column
/// for each cell of the widest row ([`coarse_edges`]); each cell edge moves to the nearest
/// grid edge.
/// - Over [`MAX_GRID_COLS`] edges, or edges [`NO_GRID_GAP`] or less apart, merge
/// ([`coarse_edges`]); each cell edge moves to the nearest grid edge. Narrow columns over a
/// point stay: import keeps them as narrow as the file gives them.
/// - A cell that ends at or before the previous one (a zero-width cell, or a cell with no
/// `\cellx` of its own) still gets a grid column of its own; cells pushed past the table's
/// right edge move back.
@@ -298,7 +294,7 @@ pub(super) fn column_grid(rows: &mut [Vec<Cell>], rights: &[Vec<i32>]) -> Vec<f3
if edges.is_empty() {
return Vec::new();
}
let grid = coarse_edges(&edges, rows.iter().map(Vec::len).max().unwrap_or(0));
let grid = coarse_edges(&edges);
// Each cell's right edge as a grid edge number (1 = the first grid column's right edge).
let mut ends: Vec<Vec<usize>> = Vec::with_capacity(rows.len());
for (row, x) in rows.iter().zip(rights) {
@@ -339,10 +335,9 @@ pub(super) fn column_grid(rows: &mut [Vec<Cell>], rights: &[Vec<i32>]) -> Vec<f3
/// The grid edges kept from the sorted, distinct, positive `edges`. The narrowest column merges
/// into the next, one at a time, so an edge moves only when it has to: while there are over
/// [`MAX_GRID_COLS`] columns, or columns of [`NO_GRID_GAP`] or less, and while a column is under
/// [`MIN_GRID_GAP`] and more columns remain than the `widest_row`'s cells. The table's right edge
/// is always kept.
fn coarse_edges(edges: &[i32], widest_row: usize) -> Vec<i32> {
/// [`MAX_GRID_COLS`] columns, or columns of [`NO_GRID_GAP`] or less. The table's right edge is
/// always kept.
fn coarse_edges(edges: &[i32]) -> Vec<i32> {
let n = edges.len();
// Each edge's neighbours among the edges still kept.
let mut left: Vec<Option<usize>> = (0..n).map(|i| i.checked_sub(1)).collect();
@@ -360,7 +355,7 @@ fn coarse_edges(edges: &[i32], widest_row: usize) -> Vec<i32> {
if !kept.get(i).copied().unwrap_or(false) || w != width(i, &left) {
continue;
}
if count <= MAX_GRID_COLS && w > NO_GRID_GAP && (w >= MIN_GRID_GAP || count <= widest_row) {
if count <= MAX_GRID_COLS && w > NO_GRID_GAP {
break;
}
// The column's right edge goes, unless it is the table's: then its left edge does.
+24 -4
View File
@@ -389,6 +389,26 @@ fn page_size_and_margins() {
assert_eq!(d.last_section, craft_wordmodel::SectionProps::default());
}
#[test]
fn narrow_grid_columns_keep_their_width() {
// Rows' edges a few points apart, as in a form exported from a spreadsheet. The table stays as
// wide as its source, through an export and back too.
let rtf = br"{\rtf1\ansi
\trowd\cellx400\cellx800 \pard\intbl a\cell b\cell\row
\trowd\cellx80\cellx480\cellx800 \pard\intbl c\cell d\cell e\cell\row
\pard after\par}";
let table = |doc: &Document| match doc.body.iter().find_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t.clone()) } else { None })
{
Some(t) => t,
None => panic!("no table"),
};
let doc = import(rtf).unwrap();
let t = table(&doc);
assert_eq!(t.grid, [4.0, 16.0, 4.0, 16.0]);
assert_eq!(t.rows[0].cells.iter().map(|c| c.props.width).collect::<Vec<_>>(), [Some(20.0), Some(20.0)]);
assert_eq!(table(&import(export(&doc).as_bytes()).unwrap()).grid, t.grid);
}
#[test]
fn table_grid_from_cell_edges_and_borders() {
// Rows whose cells don't line up share one grid: edges 2000, 3000, 9000.
@@ -565,16 +585,16 @@ fn table_grid_keeps_a_column_for_each_cell_of_the_widest_row() {
}
#[test]
fn table_grid_merges_columns_import_would_widen() {
// Columns under 6 pt that no row needs: import raises each one to 6 pt, so this table of
// 3 pt columns doubled in width. Merged, it keeps its 60 pt.
fn table_grid_keeps_narrow_columns_at_their_width() {
// Columns under 6 pt that no row needs keep their 3 pt: import no longer widens them, so the
// table keeps its 60 pt.
let mut rtf = String::from(r"{\rtf1\ansi ");
for k in 1..=20 {
rtf.push_str(&rtf_row(&[k * 60, 1200]));
}
rtf.push_str(r"\pard\par}");
let (widths, _) = grid_of(rtf.as_bytes());
assert!(widths.iter().all(|&w| w >= 6.0), "{widths:?}");
assert_eq!(widths, [3.0; 20], "{widths:?}");
let d = import(rtf.as_bytes()).unwrap();
let t = d.body.iter().find_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t) } else { None }).unwrap();
assert_eq!(t.grid.iter().sum::<f32>(), 60.0, "{:?}", t.grid);