mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 20:58:01 +00:00
craft-docx: keep a table style's w:tblInd on read and save (#2196)
* craft-docx: keep a table style's w:tblInd on read and save A table style's own indent was dropped on read, so it was gone on save. pandoc's Table style sets it to 0, and Word for Mac places a table whose style chain sets no indent about 5.4 pt further right than one set to 0. craft-wordmodel gains TableStyleParts::indent, merged through basedOn. The reader takes a dxa indent (nil is 0; pct and auto set none) and the writer emits it in schema order, 0 included. Part of storytold/wordcraft#5767. * craft-docx: a table style's w:tblInd without w:w is 0 CT_TblWidth's w:w defaults to 0, so the style resets a based-on style's indent instead of inheriting it. The test helper now fails when a saved style is missing rather than matching an empty string. * craft-docx: the tblInd override test checks the base sets an indent Without it the test would pass if the reader dropped the base style's indent, since there would be nothing to override.
This commit is contained in:
@@ -283,6 +283,15 @@ impl Reader<'_> {
|
||||
}
|
||||
t.fill = tp.child("w:shd").and_then(|e| self.pc.shd_fill(e));
|
||||
t.cell_margins = tp.child("w:tblCellMar").map(props::margins);
|
||||
// Only a twips indent (`dxa`, the default) is a length: `nil` is no indent, and `pct`
|
||||
// or `auto` have no meaning for an indent (ECMA-376 §17.4.50), so the style sets none.
|
||||
// A `w:w` left out is 0 (`CT_TblWidth`), which still overrides a based-on style's.
|
||||
t.indent = tp.child("w:tblInd").and_then(|e| match e.attr("w:type").unwrap_or("dxa") {
|
||||
"dxa" if e.attr("w:w").is_none() => Some(0.0),
|
||||
"dxa" => tw(e, "w:w").map(|i| i.clamp(-1584.0, 1584.0)),
|
||||
"nil" => Some(0.0),
|
||||
_ => None,
|
||||
});
|
||||
t.band_size = tp.child_val("w:tblStyleRowBandSize").and_then(u32_of).map(|n| n.min(1000));
|
||||
t.col_band_size = tp.child_val("w:tblStyleColBandSize").and_then(u32_of).map(|n| n.min(1000));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::{Level, LevelSuffix, ParaProps, Style, StyleKind, TablePart, VAlign, W, Writer, props, xml};
|
||||
use crate::write::props::open_change;
|
||||
use craft_wordmodel::Document;
|
||||
use craft_wordmodel::styles::TableStyleParts;
|
||||
|
||||
/// Built-in names Word keeps in lower case in styles.xml.
|
||||
fn file_style_name(name: &str) -> String {
|
||||
@@ -61,6 +62,31 @@ pub(super) fn styles_xml(wr: &mut Writer<'_>) -> Vec<u8> {
|
||||
|
||||
/// One `w:style` element. A tracked change of its paragraph/run properties is nested in the
|
||||
/// corresponding property element as `w:pPrChange` / `w:rPrChange`.
|
||||
/// A table style's own table properties (`w:tblPr`), in ECMA-376 order.
|
||||
fn table_style_tblpr(w: &mut W, t: &TableStyleParts) {
|
||||
if t.borders.is_none() && t.cell_margins.is_none() && t.indent.is_none() && t.band_size.is_none() && t.col_band_size.is_none() {
|
||||
return;
|
||||
}
|
||||
w.open("w:tblPr", &[]);
|
||||
if let Some(n) = t.band_size {
|
||||
w.val("w:tblStyleRowBandSize", &n.min(1000).to_string());
|
||||
}
|
||||
if let Some(n) = t.col_band_size {
|
||||
w.val("w:tblStyleColBandSize", &n.min(1000).to_string());
|
||||
}
|
||||
// Kept even at 0: Word places a table whose style chain sets no indent differently.
|
||||
if let Some(i) = t.indent {
|
||||
w.empty("w:tblInd", &[("w:w", &crate::units::twips(i)), ("w:type", "dxa")]);
|
||||
}
|
||||
if let Some(b) = &t.borders {
|
||||
props::borders(w, "w:tblBorders", b, Some("w:insideH"), &[]);
|
||||
}
|
||||
if let Some(m) = &t.cell_margins {
|
||||
props::margins(w, "w:tblCellMar", m);
|
||||
}
|
||||
w.close("w:tblPr");
|
||||
}
|
||||
|
||||
fn style_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style, flagged: &[StyleKind]) {
|
||||
let ty = match st.kind {
|
||||
StyleKind::Paragraph => "paragraph",
|
||||
@@ -114,22 +140,7 @@ fn style_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style, flagged: &[StyleKind])
|
||||
}
|
||||
style_property_xml(wr, w, st);
|
||||
if let Some(t) = &st.table {
|
||||
if t.borders.is_some() || t.cell_margins.is_some() || t.band_size.is_some() || t.col_band_size.is_some() {
|
||||
w.open("w:tblPr", &[]);
|
||||
if let Some(n) = t.band_size {
|
||||
w.val("w:tblStyleRowBandSize", &n.min(1000).to_string());
|
||||
}
|
||||
if let Some(n) = t.col_band_size {
|
||||
w.val("w:tblStyleColBandSize", &n.min(1000).to_string());
|
||||
}
|
||||
if let Some(b) = &t.borders {
|
||||
props::borders(w, "w:tblBorders", b, Some("w:insideH"), &[]);
|
||||
}
|
||||
if let Some(m) = &t.cell_margins {
|
||||
props::margins(w, "w:tblCellMar", m);
|
||||
}
|
||||
w.close("w:tblPr");
|
||||
}
|
||||
table_style_tblpr(w, t);
|
||||
// The conditional formatting parts (ECMA-376 §17.7.6): paragraph and run properties,
|
||||
// then cell borders, shading and vertical alignment. The whole table's text formatting
|
||||
// is the style's own (above).
|
||||
|
||||
@@ -47,6 +47,7 @@ mod section_text_direction;
|
||||
mod section_valign;
|
||||
mod settings_merge;
|
||||
mod strict_drawings;
|
||||
mod table_style_indent;
|
||||
mod text_alignment;
|
||||
mod text_boxes;
|
||||
mod theme_font_slots;
|
||||
|
||||
@@ -571,6 +571,7 @@ fn table_style_formatting_round_trips() {
|
||||
borders: Some(Borders { top: Some(Border::single(1.0)), ..Default::default() }),
|
||||
fill: Some(Rgb(0xDD, 0xEB, 0xF7)),
|
||||
cell_margins: Some([1.0, 14.4, 0.0, 14.4]),
|
||||
indent: Some(0.0),
|
||||
header_chr: CharProps { italic: Some(true), ..Default::default() },
|
||||
header_fill: Some(Rgb(0xFF, 0xFF, 0)),
|
||||
header_borders: Some(Borders::all(Border::single(1.5))),
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! The indent of a table style (`w:tblStyle/w:tblPr/w:tblInd`, ECMA-376 §17.4.50). pandoc's
|
||||
//! "Table" style sets it to 0; dropped on save, Word for Mac moved every table of a manuscript
|
||||
//! about 5.4 pt to the right (it places a table whose style chain sets no indent at the margin,
|
||||
//! but one set to 0 with its first cell's text at the margin).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str, styles: &str) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let styles = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{styles}</w:styles>"#
|
||||
);
|
||||
let parts = [
|
||||
("_rels/.rels", root.to_string()),
|
||||
("word/document.xml", doc),
|
||||
("word/_rels/document.xml.rels", doc_rels.to_string()),
|
||||
("word/styles.xml", styles),
|
||||
];
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, xml) in &parts {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
fn style_xml(bytes: &[u8], id: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/styles.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
let key = format!(r#"w:styleId="{id}""#);
|
||||
let style = s.split("<w:style ").find(|x| x.contains(&key)).unwrap_or_else(|| panic!("style {id} missing from the saved styles.xml"));
|
||||
style.split("</w:style>").next().unwrap_or(style).to_string()
|
||||
}
|
||||
|
||||
const BODY: &str = r#"<w:tbl><w:tblPr><w:tblStyle w:val="Indented"/><w:tblW w:w="0" w:type="auto"/></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>Cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/>"#;
|
||||
|
||||
#[test]
|
||||
fn a_table_style_indent_of_zero_survives_a_save() {
|
||||
let styles = r#"<w:style w:type="table" w:default="1" w:styleId="Table"><w:name w:val="Table"/><w:tblPr><w:tblInd w:w="0" w:type="dxa"/><w:tblCellMar><w:left w:w="108" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style><w:style w:type="table" w:styleId="Indented"><w:name w:val="Indented"/><w:basedOn w:val="Table"/><w:tblPr><w:tblInd w:w="720" w:type="dxa"/></w:tblPr></w:style><w:style w:type="table" w:styleId="Plain"><w:name w:val="Plain"/><w:tblPr><w:tblCellMar><w:left w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>"#;
|
||||
let d = craft_docx::read(&docx(BODY, styles)).unwrap();
|
||||
let parts = |id: &str| d.styles.get(id).and_then(|s| s.table.clone()).unwrap_or_default();
|
||||
assert_eq!(parts("Table").indent, Some(0.0));
|
||||
assert_eq!(parts("Indented").indent, Some(36.0));
|
||||
assert_eq!(parts("Plain").indent, None, "no w:tblInd stays unset");
|
||||
|
||||
let out = craft_docx::write(&d).unwrap();
|
||||
let table = style_xml(&out, "Table");
|
||||
assert!(table.contains(r#"<w:tblInd w:w="0" w:type="dxa"/>"#), "{table}");
|
||||
let indented = style_xml(&out, "Indented");
|
||||
assert!(indented.contains(r#"<w:tblInd w:w="720" w:type="dxa"/>"#), "{indented}");
|
||||
let plain = style_xml(&out, "Plain");
|
||||
assert!(!plain.contains("w:tblInd"), "{plain}");
|
||||
// ECMA-376 order in w:tblPr: w:tblInd before w:tblCellMar.
|
||||
assert!(table.find("w:tblInd") < table.find("w:tblCellMar"), "{table}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_style_indent_that_is_no_length_sets_none() {
|
||||
// `pct` and `auto` are no lengths for an indent; `nil` is none.
|
||||
let style = |ty: &str| {
|
||||
format!(
|
||||
r#"<w:style w:type="table" w:styleId="Indented"><w:name w:val="Indented"/><w:tblPr><w:tblInd w:w="720" w:type="{ty}"/></w:tblPr></w:style>"#
|
||||
)
|
||||
};
|
||||
for (ty, want) in [("pct", None), ("auto", None), ("nil", Some(0.0)), ("dxa", Some(36.0))] {
|
||||
let d = craft_docx::read(&docx(BODY, &style(ty))).unwrap();
|
||||
let got = d.styles.get("Indented").and_then(|s| s.table.clone()).unwrap_or_default().indent;
|
||||
assert_eq!(got, want, "w:type={ty}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_style_indent_without_a_width_is_zero_and_overrides_its_base() {
|
||||
// `CT_TblWidth`'s `w:w` defaults to 0, so a based-on style's indent is reset, not inherited.
|
||||
let styles = r#"<w:style w:type="table" w:styleId="Base"><w:name w:val="Base"/><w:tblPr><w:tblInd w:w="720" w:type="dxa"/></w:tblPr></w:style><w:style w:type="table" w:styleId="Indented"><w:name w:val="Indented"/><w:basedOn w:val="Base"/><w:tblPr><w:tblInd w:type="dxa"/></w:tblPr></w:style>"#;
|
||||
let d = craft_docx::read(&docx(BODY, styles)).unwrap();
|
||||
let own_of = |d: &craft_wordmodel::Document, id: &str| d.styles.get(id).and_then(|s| s.table.clone()).unwrap_or_default().indent;
|
||||
let own = |d: &craft_wordmodel::Document| own_of(d, "Indented");
|
||||
assert_eq!(own_of(&d, "Base"), Some(36.0), "the base sets an indent to override");
|
||||
assert_eq!(d.styles.table_style("Base").map(|s| s.parts.indent), Some(Some(36.0)));
|
||||
assert_eq!(own(&d), Some(0.0));
|
||||
assert_eq!(d.styles.table_style("Indented").map(|s| s.parts.indent), Some(Some(0.0)), "the base's 36 pt is overridden");
|
||||
|
||||
let out = craft_docx::write(&d).unwrap();
|
||||
let indented = style_xml(&out, "Indented");
|
||||
assert!(indented.contains(r#"<w:tblInd w:w="0" w:type="dxa"/>"#), "{indented}");
|
||||
assert_eq!(own(&craft_docx::read(&out).unwrap()), Some(0.0));
|
||||
}
|
||||
@@ -69,6 +69,10 @@ pub struct TableStyleParts {
|
||||
pub fill: Option<Rgb>,
|
||||
/// Cell margins, points: [top, left, bottom, right] (`w:tblCellMar`).
|
||||
pub cell_margins: Option<[f32; 4]>,
|
||||
/// Indent of the table from the leading margin, points (`w:tblInd`). Kept even when 0:
|
||||
/// Word places a table whose style chain sets no indent differently from one set to 0.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub indent: Option<f32>,
|
||||
pub header_fill: Option<Rgb>,
|
||||
pub header_chr: CharProps,
|
||||
/// Cell borders of the header row (`firstRow` region's `w:tcBorders`): `between` is the
|
||||
@@ -326,6 +330,7 @@ impl TableStyleParts {
|
||||
self.band_chr.overlay(&patch.band_chr);
|
||||
self.fill = patch.fill.or(self.fill);
|
||||
self.cell_margins = patch.cell_margins.or(self.cell_margins);
|
||||
self.indent = patch.indent.or(self.indent);
|
||||
self.header_fill = patch.header_fill.or(self.header_fill);
|
||||
self.header_chr.overlay(&patch.header_chr);
|
||||
self.band_fill = patch.band_fill.or(self.band_fill);
|
||||
|
||||
Reference in New Issue
Block a user