f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
use super::{Address, AddressError, AddressStep, TextBlockKind, text_blocks};
use crate::body::{Block, Body};
use crate::ns::W;
use crate::quirks::BodyFieldResults;
use crate::reader::PartReader;
use crate::styles::Styles;
use f_office_xml::{Document, Limits};

/// The blocks of a body of `xml`, read as the body of a document whose fields keep their stored
/// results.
fn blocks_of(xml: &str) -> Vec<Block> {
    let doc = Document::parse(
        format!(r#"<w:body xmlns:w="{W}">{xml}</w:body>"#).as_bytes(),
        &Limits::default(),
    )
    .unwrap();
    let root = doc.root().unwrap();
    Body::read(
        &mut PartReader::new(&doc),
        root,
        (
            crate::reader::settings::ReaderSettings::base()
                .with_body_results(BodyFieldResults::ComputesFields)
                .with_section_ends(crate::quirks::ContinuousSectionEnd::OnlyBlockKeepsLine),
            crate::mode::ModeRules::default(),
        ),
    )
    .blocks
}

fn paragraph(text: &str) -> String {
    format!(r#"<w:p><w:r><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#)
}

fn cell(content: &str) -> String {
    format!("<w:tc>{content}</w:tc>")
}

#[test]
fn reads_and_writes_each_kind_of_address() {
    for text in [
        "p1",
        "p12",
        "t2",
        "t2/r4",
        "t2/r4/c1",
        "t2/r4/c1/p1",
        "t1/r1/c2/t3/r1/c1/p2",
        "h1/p3",
        "f2/t1/r1/c1/p1",
        "n4/p1",
        "e1/t2",
        "p5/b1/p2",
        "h1/p3/b1/p1",
        "p5/b1/p2/b1/p1",
        "t1/r1/c1/p1/b2/t1/r1/c1/p1",
    ] {
        let address: Address = text.parse().unwrap();
        assert_eq!(address.to_string(), text);
    }
    let address: Address = "t2/r4/c1/p1".parse().unwrap();
    let n = |n| std::num::NonZeroUsize::new(n).unwrap();
    assert_eq!(
        address.steps(),
        [
            AddressStep::Table(n(2)),
            AddressStep::Row(n(4)),
            AddressStep::Cell(n(1)),
            AddressStep::Paragraph(n(1)),
        ]
    );
}

#[test]
fn refuses_a_step_that_is_not_a_kind_and_a_number_from_1() {
    assert_eq!("".parse::<Address>(), Err(AddressError::Empty));
    for bad in [
        "x3",
        "p",
        "p0",
        "p01",
        "p+1",
        "p1a",
        "P1",
        "p99999999999999999999999",
        "p1/",
    ] {
        let error = bad.parse::<Address>().unwrap_err();
        assert!(
            matches!(error, AddressError::Step { .. }),
            "{bad}: {error:?}"
        );
        assert!(
            error.to_string().contains("such as p12 or t2/r4/c1/p1"),
            "{error}"
        );
    }
}

#[test]
fn refuses_a_step_where_the_grammar_allows_another_kind() {
    for (bad, step) in [
        ("p1/p2", "p2"),
        ("r1", "r1"),
        ("t1/c1", "c1"),
        ("t1/r1/p1", "p1"),
        ("t1/r1/c1/r1", "r1"),
        ("p1/h1", "h1"),
        ("h1/h2", "h2"),
        ("b1", "b1"),
        ("t1/b1", "b1"),
        ("h1/b1", "b1"),
        ("p1/b1/r1", "r1"),
    ] {
        let error = bad.parse::<Address>().unwrap_err();
        let AddressError::Order { step: quoted, .. } = &error else {
            panic!("{bad}: {error:?}");
        };
        assert_eq!(quoted, step);
        assert!(error.to_string().contains("as in t2/r4/c1/p1"), "{error}");
    }
}

#[test]
fn refuses_an_address_that_ends_after_a_story_or_a_text_box() {
    for bad in ["h1", "n2", "p1/b1", "t1/r1/c1/p2/b3"] {
        let error = bad.parse::<Address>().unwrap_err();
        assert!(
            matches!(error, AddressError::Unfinished { .. }),
            "{bad}: {error:?}"
        );
        assert!(error.to_string().contains("as in h1/p3/b1/p1"), "{error}");
    }
}

#[test]
fn tells_an_address_of_the_body_from_one_of_another_story_or_a_text_box() {
    let in_body = |text: &str| text.parse::<Address>().unwrap().in_body();
    assert!(in_body("p1"));
    assert!(in_body("t2/r4/c1/p1"));
    assert!(!in_body("h1/p1"));
    assert!(!in_body("e3/t1"));
    assert!(!in_body("p5/b1/p2"));
}

#[test]
fn numbers_the_paragraphs_and_tables_of_the_body_and_of_each_cell_apart() {
    let inner = format!("<w:tbl><w:tr>{}</w:tr></w:tbl>", cell(&paragraph("inner")));
    let body = format!(
        "{}<w:tbl><w:tr>{}{}</w:tr><w:tr>{}</w:tr></w:tbl>{}",
        paragraph("one"),
        cell(&paragraph("a")),
        cell(&format!("{}{inner}", paragraph("b"))),
        cell(&format!("{}{}", paragraph("c"), paragraph("d"))),
        paragraph("two"),
    );
    let blocks = text_blocks(&blocks_of(&body), &[], (&Styles::without_part(), None));
    let listed: Vec<(String, String)> = blocks
        .iter()
        .map(|block| {
            let what = match &block.kind {
                TextBlockKind::Paragraph { text, .. } => text.clone(),
                TextBlockKind::Table { rows } => format!("{rows} rows"),
            };
            (block.address.to_string(), what)
        })
        .collect();
    let expected = [
        ("p1", "one"),
        ("t1", "2 rows"),
        ("t1/r1/c1/p1", "a"),
        ("t1/r1/c2/p1", "b"),
        ("t1/r1/c2/t1", "1 rows"),
        ("t1/r1/c2/t1/r1/c1/p1", "inner"),
        ("t1/r2/c1/p1", "c"),
        ("t1/r2/c1/p2", "d"),
        ("p2", "two"),
    ]
    .map(|(a, b)| (a.to_owned(), b.to_owned()));
    assert_eq!(listed, expected);
    // Without placed lines, no block has a page.
    assert!(blocks.iter().all(|block| block.page_indices.is_none()));
    // Each address reads back to itself.
    for block in &blocks {
        let again: Address = block.address.to_string().parse().unwrap();
        assert_eq!(again, block.address);
    }
}

#[test]
fn gives_a_paragraph_its_style_and_the_text_of_its_runs() {
    let body = concat!(
        r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr>"#,
        r#"<w:r><w:t>Fees</w:t><w:tab/><w:t>and</w:t><w:br/><w:t>costs</w:t></w:r></w:p>"#,
        "<w:p><w:r><w:t>plain</w:t></w:r></w:p>",
    );
    let blocks = text_blocks(&blocks_of(body), &[], (&Styles::without_part(), None));
    assert_eq!(
        blocks.first().map(|block| &block.kind),
        Some(&TextBlockKind::Paragraph {
            style: Some("Heading1".to_owned()),
            text: "Fees\tand\ncosts".to_owned(),
        })
    );
    assert_eq!(
        blocks.get(1).map(|block| &block.kind),
        Some(&TextBlockKind::Paragraph {
            style: None,
            text: "plain".to_owned(),
        })
    );
}

#[test]
fn shows_a_computed_field_once_and_leaves_out_field_codes() {
    // A PAGE field shows a marker, and a DATE field its stored result once, never its code.
    let field = |code: &str, result: &str| {
        format!(
            r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve">{code}</w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>{result}</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>"#
        )
    };
    let body = format!(
        "<w:p><w:r><w:t xml:space=\"preserve\">Page </w:t></w:r>{}<w:r><w:t xml:space=\"preserve\"> of </w:t></w:r>{}<w:r><w:t xml:space=\"preserve\">, </w:t></w:r>{}</w:p>",
        field(" PAGE ", "4"),
        field(" NUMPAGES ", "9"),
        field(r#" DATE \@ "yyyy" "#, "2020"),
    );
    let blocks = text_blocks(&blocks_of(&body), &[], (&Styles::without_part(), None));
    let Some(TextBlockKind::Paragraph { text, .. }) = blocks.first().map(|block| &block.kind)
    else {
        panic!("no paragraph");
    };
    assert_eq!(text, "Page {PAGE} of {NUMPAGES}, 2020");
}

#[test]
fn shows_each_break_as_a_new_line() {
    let body = concat!(
        r#"<w:p><w:r><w:t>a</w:t><w:br w:type="page"/><w:t>b</w:t><w:br w:type="column"/>"#,
        r#"<w:t>c</w:t></w:r></w:p>"#,
    );
    let blocks = text_blocks(&blocks_of(body), &[], (&Styles::without_part(), None));
    assert!(matches!(
        blocks.first().map(|block| &block.kind),
        Some(TextBlockKind::Paragraph { text, .. }) if text == "a\nb\nc"
    ));
}

#[test]
fn gives_the_span_of_each_blocks_and_rows_element_also_inside_a_content_control() {
    let first = paragraph("one");
    let row = format!("<w:tr>{}</w:tr>", cell(&paragraph("a")));
    let table = format!("<w:tbl><w:sdt><w:sdtContent>{row}</w:sdtContent></w:sdt>{row}</w:tbl>");
    let wrapped = paragraph("two");
    let body = format!("{first}{table}<w:sdt><w:sdtContent>{wrapped}</w:sdtContent></w:sdt>");
    let xml = format!(r#"<w:body xmlns:w="{W}">{body}</w:body>"#);
    let blocks = text_blocks(&blocks_of(&body), &[], (&Styles::without_part(), None));
    let text = |range: &Option<std::ops::Range<usize>>| xml[range.clone().unwrap()].to_owned();
    let sources: Vec<(String, String)> = blocks
        .iter()
        .map(|block| (block.address.to_string(), text(&block.source)))
        .collect();
    let expected = [
        ("p1", first.as_str()),
        ("t1", table.as_str()),
        ("t1/r1/c1/p1", paragraph("a").as_str()),
        ("t1/r2/c1/p1", paragraph("a").as_str()),
        ("p2", wrapped.as_str()),
    ]
    .map(|(a, b)| (a.to_owned(), b.to_owned()));
    assert_eq!(sources, expected);
    let rows: Vec<String> = blocks[1].row_sources.iter().map(text).collect();
    assert_eq!(rows, [row.clone(), row]);
    assert_eq!(blocks[0].row_sources, []);
}

#[test]
fn gives_a_heading_the_outline_level_of_its_own_properties_or_of_its_styles() {
    let styles = Document::parse(
        format!(
            r#"<w:styles xmlns:w="{W}"><w:style w:type="paragraph" w:styleId="H1"><w:pPr><w:outlineLvl w:val="0"/></w:pPr></w:style><w:style w:type="paragraph" w:styleId="H1b"><w:basedOn w:val="H1"/></w:style><w:style w:type="paragraph" w:styleId="H3"><w:pPr><w:outlineLvl w:val="2"/></w:pPr></w:style></w:styles>"#
        )
        .as_bytes(),
        &Limits::default(),
    )
    .unwrap();
    let styles = Styles::read(&mut PartReader::new(&styles), styles.root().unwrap());
    let in_style = |style: &str, own: &str| {
        format!(
            r#"<w:p><w:pPr><w:pStyle w:val="{style}"/>{own}</w:pPr><w:r><w:t>x</w:t></w:r></w:p>"#
        )
    };
    let body = [
        in_style("H1", ""),
        in_style("H1b", ""),
        in_style("H3", ""),
        in_style("H3", r#"<w:outlineLvl w:val="9"/>"#),
        in_style("Missing", r#"<w:outlineLvl w:val="4"/>"#),
        paragraph("plain"),
        format!("<w:tbl><w:tr>{}</w:tr></w:tbl>", cell(&in_style("H1", ""))),
    ]
    .concat();
    let levels: Vec<Option<u8>> = text_blocks(&blocks_of(&body), &[], (&styles, None))
        .iter()
        .map(|block| block.outline_level)
        .collect();
    assert_eq!(
        levels,
        [
            Some(0),
            Some(0),
            Some(2),
            None,
            Some(4),
            None,
            None,
            Some(0)
        ]
    );
}