f-office 0.2.3

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! Layout tests of fields: page references, dates, page counts and style references.

use super::{
    CARLITO_RUN, RELATIONSHIPS, SECTION, anchored_at, capacity, carlito, carlito_line, docx, field,
    lines, para, render, text_box,
};

#[test]
fn shows_the_page_of_a_bookmark_in_a_pageref_field() {
    // The field's stored result is "99", and its bookmark starts the paragraph on page 2.
    let reference = format!("<w:p>{}</w:p>", field(r" PAGEREF target \h "));
    // The error text takes the format of the field's code run, here Carlito.
    let missing = format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:fldChar w:fldCharType="begin"/></w:r><w:r>{CARLITO_RUN}<w:instrText> PAGEREF elsewhere </w:instrText></w:r><w:r>{CARLITO_RUN}<w:fldChar w:fldCharType="separate"/></w:r><w:r>{CARLITO_RUN}<w:t>99</w:t></w:r><w:r>{CARLITO_RUN}<w:fldChar w:fldCharType="end"/></w:r></w:p>"#
    );
    let body = format!(
        r#"{reference}{missing}<w:p><w:r><w:br w:type="page"/></w:r></w:p><w:p><w:bookmarkStart w:id="0" w:name="target"/><w:r>{CARLITO_RUN}<w:t>Here</w:t></w:r><w:bookmarkEnd w:id="0"/></w:p><w:sectPr>{SECTION}</w:sectPr>"#
    );
    let pages = lines(&render(&docx(&body, &[], "")));
    let texts: Vec<&str> = pages[0].iter().map(|(_, t)| t.as_str()).collect();
    // A field whose bookmark is missing shows Word's error text.
    assert_eq!(texts, ["2", "Error! Bookmark not defined."]);
}

#[test]
fn shows_the_bookmark_page_of_the_second_pass_when_it_moves_the_bookmark() {
    // A full page whose second paragraph anchors a text box at the top of the page that wraps
    // top and bottom. The first pass lays out the reference before the anchor without the box
    // and finds the bookmark in the last line of page 1. The second pass keeps all the text
    // below the box, which moves the bookmark to page 2, and the third pass shows that page.
    // The anchor stays on page 1, so the box does too.
    let (_, line) = carlito_line();
    let reference = format!("<w:p>{}</w:p>", field(r" PAGEREF target \h "));
    let filler: String = (0..capacity(line) - 3)
        .map(|n| para(&format!("Line {n}")))
        .collect();
    let place = anchored_at("page", 0, 457_200);
    let drawing = text_box(&format!(
        r#"{place}<wp:extent cx="1371600" cy="457200"/><wp:wrapTopAndBottom/>"#
    ));
    let body = format!(
        r#"{reference}<w:p>{drawing}<w:r>{CARLITO_RUN}<w:t>Anchor</w:t></w:r></w:p>{filler}<w:p><w:bookmarkStart w:id="0" w:name="target"/><w:r>{CARLITO_RUN}<w:t>Here</w:t></w:r><w:bookmarkEnd w:id="0"/></w:p><w:sectPr>{SECTION}</w:sectPr>"#
    );
    let pages = lines(&render(&docx(&body, &[], "")));
    let here = pages
        .iter()
        .position(|page| page.iter().any(|(_, t)| t == "Here"));
    assert_eq!(here, Some(1), "{pages:?}");
    let first = pages[0]
        .iter()
        .find(|(_, t)| t != "Box")
        .map(|(_, t)| t.as_str());
    assert_eq!(first, Some("2"), "{pages:?}");
}

#[test]
fn shows_the_layout_time_in_date_fields_and_else_the_stored_result() {
    let body = format!(
        r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> DATE \@ "d MMMM yyyy" </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r>{CARLITO_RUN}<w:t>1 May 2020</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
    );
    let file = docx(&body, &[], "");
    let fonts = carlito();
    let text = |options: &crate::Options| {
        let document = crate::Document::open(&file, &fonts, options).unwrap().value;
        lines(document.display_list())[0][0].1.clone()
    };
    assert_eq!(text(&crate::Options::base()), "1 May 2020");
    let now = crate::DateTime {
        year: 2026,
        month: 9,
        day: 25,
        hour: 14,
        minute: 33,
        second: 12,
    };
    let options = crate::Options {
        now: Some(now),
        ..crate::Options::base()
    };
    assert_eq!(text(&options), "25 September 2026");
}

#[test]
fn shows_the_layout_time_as_the_last_saved_time_in_a_footer() {
    let foot = format!(
        r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> DOCPROPERTY  LastSavedTime  \* MERGEFORMAT </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r>{CARLITO_RUN}<w:t>19/09/2014 9:35 AM</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#
    );
    let body = format!(
        r#"{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:footerReference w:type="default" r:id="f1"/>{SECTION}</w:sectPr>"#,
        para("Body")
    );
    let file = docx(&body, &[("f1", &foot)], "");
    let fonts = carlito();
    let footer = |options: &crate::Options| {
        let document = crate::Document::open(&file, &fonts, options).unwrap().value;
        lines(document.display_list())[0]
            .last()
            .map_or_default(|line| line.1.clone())
    };
    assert_eq!(footer(&crate::Options::base()), "19/09/2014 9:35 AM");
    let now = crate::DateTime {
        year: 2026,
        month: 9,
        day: 25,
        hour: 17,
        minute: 56,
        second: 13,
    };
    let options = crate::Options {
        now: Some(now),
        ..crate::Options::base()
    };
    assert_eq!(footer(&options), "9/25/2026 5:56 PM");
}

#[test]
fn a_page_count_in_the_body_shows_the_pages_of_the_whole_document() {
    // Inside a table too, and a page number in the body stays the page's own.
    let counted = format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:t xml:space="preserve">Page </w:t></w:r>{}<w:r>{CARLITO_RUN}<w:t xml:space="preserve"> of </w:t></w:r>{}<w:r><w:br w:type="page"/></w:r></w:p>"#,
        field("PAGE"),
        field("NUMPAGES")
    );
    let in_table = format!(
        r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p>{}</w:p></w:tc></w:tr></w:tbl>"#,
        field("NUMPAGES")
    );
    let body = format!(
        r"{counted}{}{in_table}<w:sectPr>{SECTION}</w:sectPr>",
        r#"<w:p><w:r><w:br w:type="page"/></w:r></w:p>"#
    );
    let pages = lines(&render(&docx(&body, &[], "")));
    assert_eq!(pages.len(), 3);
    assert_eq!(pages[0][0].1.replace(' ', ""), "Page1of3");
    assert_eq!(pages[2][0].1, "3");
}

/// A paragraph of Carlito text with a paragraph style.
fn styled_para(style: &str, text: &str) -> String {
    para(text).replacen(
        "<w:p>",
        &format!(r#"<w:p><w:pPr><w:pStyle w:val="{style}"/></w:pPr>"#),
        1,
    )
}

#[test]
fn shows_the_first_heading_of_each_page_in_a_styleref_field_of_the_header() {
    let head = format!(
        r#"<w:p><w:fldSimple w:instr="STYLEREF Part"><w:r>{CARLITO_RUN}<w:t>Old</w:t></w:r></w:fldSimple></w:p>"#
    );
    let page_break = r#"<w:p><w:r><w:br w:type="page"/></w:r></w:p>"#;
    let body = format!(
        r#"{}{}{page_break}{}{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:headerReference w:type="default" r:id="h1"/>{SECTION}</w:sectPr>"#,
        styled_para("Part", "Alpha"),
        para("Text"),
        para("More"),
        styled_para("Part", "Beta"),
    );
    let pages = lines(&render(&docx(&body, &[("h1", &head)], "")));
    let texts =
        |page: &[(f64, String)]| -> Vec<String> { page.iter().map(|(_, t)| t.clone()).collect() };
    assert_eq!(texts(&pages[0]), ["Alpha", "Alpha", "Text"]);
    // The second page starts with a paragraph of another style, and its heading comes later.
    assert_eq!(texts(&pages[1]), ["Beta", "More", "Beta"]);
}

#[test]
fn sizes_a_header_by_the_styleref_text_of_its_page() {
    let head = format!(
        r#"<w:p><w:fldSimple w:instr="STYLEREF Part"><w:r>{CARLITO_RUN}<w:t>Old</w:t></w:r></w:fldSimple></w:p>"#
    );
    // The heading takes three lines in the header as in the body, and the header reaches below
    // the top margin with them.
    let long = "Words that fill the header ".repeat(5);
    let body = format!(
        r#"{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:headerReference w:type="default" r:id="h1"/>{SECTION}</w:sectPr>"#,
        styled_para("Part", long.trim()),
    );
    let pages = lines(&render(&docx(&body, &[("h1", &head)], "")));
    let ys: Vec<f64> = pages[0].iter().map(|(y, _)| *y).collect();
    assert_eq!(ys.len(), 6, "{pages:?}");
    // The body starts below the header's last line, a line apart at least.
    assert!(
        ys.windows(2).all(|pair| pair[1] - pair[0] > 10.0),
        "{pages:?}"
    );
}