f-office 0.2.3

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! Layout tests of the hyperlinks and bookmarks of the story text: a `w:hyperlink` with an
//! external address or a bookmark, a field that links, a link inside a link, and where a
//! bookmark lies in the text.

use f_office_docx::testing::{self, RELATIONSHIPS, WordParts as _};

use super::{CARLITO_RUN, Document, Options, carlito};
use crate::{LinkTarget, StoryLink, StoryParagraph, TextStory};

/// The body paragraphs of the DOCX file with the body `body`, whose part has the external
/// hyperlink relationship `rIdWeb` to `https://example.com/page`.
fn body_text(body: &str) -> Vec<StoryParagraph> {
    let docx = testing::docx(body)
        .external_relationship(
            "word/document.xml",
            "rIdWeb",
            "hyperlink",
            "https://example.com/page",
        )
        .plain_styles()
        .zip()
        .unwrap();
    let document = Document::open(&docx, &carlito(), &Options::base())
        .unwrap()
        .value;
    document.story_text(TextStory::Body)
}

/// A paragraph of the markup `inner`.
fn paragraph(inner: &str) -> String {
    format!(r#"<w:p xmlns:r="{RELATIONSHIPS}">{inner}</w:p>"#)
}

/// A run of Carlito with the content `content`.
fn run(content: &str) -> String {
    format!("<w:r>{CARLITO_RUN}{content}</w:r>")
}

/// A run of the text `text`.
fn text(text: &str) -> String {
    run(&format!(r#"<w:t xml:space="preserve">{text}</w:t>"#))
}

/// The runs of a field of the code `code` whose stored result is the runs `result`.
fn field(code: &str, result: &str) -> String {
    format!(
        "{}{}{}{result}{}",
        run(r#"<w:fldChar w:fldCharType="begin"/>"#),
        run(&format!(
            r#"<w:instrText xml:space="preserve">{code}</w:instrText>"#
        )),
        run(r#"<w:fldChar w:fldCharType="separate"/>"#),
        run(r#"<w:fldChar w:fldCharType="end"/>"#),
    )
}

/// The text of each link of `paragraph`, with where it goes and its tooltip.
fn links(paragraph: &StoryParagraph) -> Vec<(&str, LinkTarget, Option<&str>)> {
    (paragraph.links.iter())
        .map(|link| {
            let shown = paragraph
                .text
                .get(link.start_byte as usize..link.end_byte as usize)
                .unwrap();
            (shown, link.target.clone(), link.tooltip.as_deref())
        })
        .collect()
}

/// The name and the byte of each bookmark of `paragraph`.
fn bookmarks(paragraph: &StoryParagraph) -> Vec<(&str, u32)> {
    (paragraph.bookmarks.iter())
        .map(|bookmark| (bookmark.name.as_str(), bookmark.offset_byte))
        .collect()
}

fn bookmark(name: &str) -> LinkTarget {
    LinkTarget::Bookmark(name.to_owned())
}

#[test]
fn gives_a_hyperlink_its_text_and_its_external_address_or_bookmark() {
    let body = paragraph(&format!(
        r#"{}<w:hyperlink r:id="rIdWeb" w:anchor="part" w:tooltip="The page">{}</w:hyperlink>{}<w:hyperlink w:anchor="Target">{}</w:hyperlink>{}"#,
        text("Go to "),
        text("the web"),
        text(" or "),
        text("back"),
        text("."),
    ));
    let story = body_text(&body);
    assert_eq!(story[0].text, "Go to the web or back.");
    assert_eq!(
        links(&story[0]),
        [
            (
                "the web",
                LinkTarget::External("https://example.com/page#part".to_owned()),
                Some("The page")
            ),
            ("back", bookmark("Target"), None),
        ]
    );
}

#[test]
fn gives_a_field_that_links_its_shown_result_and_a_link_inside_it_its_own() {
    // An entry of a table of contents: a hyperlink to the heading's bookmark, whose page number
    // is a page reference that links too.
    let page = field(r" PAGEREF _Toc1 \h ", &text("9"));
    let entry = field(
        r#" HYPERLINK \l "_Toc1" \o "To the heading" "#,
        &format!("{}{}{page}", text("Heading"), run("<w:tab/>")),
    );
    let heading = format!(
        r#"<w:bookmarkStart w:id="1" w:name="_Toc1"/>{}<w:bookmarkEnd w:id="1"/>"#,
        text("Heading")
    );
    let story = body_text(&(paragraph(&entry) + &paragraph(&heading)));
    assert_eq!(story[0].text, "Heading\t1");
    assert_eq!(
        links(&story[0]),
        [
            ("Heading\t1", bookmark("_Toc1"), Some("To the heading")),
            ("1", bookmark("_Toc1"), None),
        ]
    );
    assert_eq!(bookmarks(&story[1]), [("_Toc1", 0)]);
}

#[test]
fn places_a_bookmark_at_the_first_glyph_after_its_start() {
    let body = paragraph(&format!(
        r#"{}<w:bookmarkStart w:id="1" w:name="here"/>{}<w:bookmarkEnd w:id="1"/>"#,
        text("Before "),
        text("after"),
    ));
    let story = body_text(&body);
    assert_eq!(bookmarks(&story[0]), [("here", 7)]);
    assert_eq!(story[0].links, Vec::<StoryLink>::new());
}