f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! Floating tables in a table cell, floating tables that follow each other, and the text after a
//! floating table.

use f_office_units::Length;

use crate::layout::testing::{
    NORMAL, filler, find, find_all, lay_out, on_base_with, p, pass_with, table,
};
use crate::numbering::Numbering;
use crate::quirks::FloatingTableBreaks;

/// A floating table 3000 twips wide that hangs on the text, with the attributes `placement`
/// of its `w:tblpPr` and one row for each of `labels`.
fn floating(placement: &str, labels: &[&str]) -> String {
    let properties =
        format!(r#"<w:tblpPr w:vertAnchor="text"{placement}/><w:tblW w:w="3000" w:type="dxa"/>"#);
    let cells: Vec<String> = labels.iter().map(|label| p(label)).collect();
    let rows: Vec<(&str, [&str; 1])> = cells.iter().map(|cell| ("", [cell.as_str()])).collect();
    let rows: Vec<(&str, &[&str])> = rows
        .iter()
        .map(|(props, cell)| (*props, &cell[..]))
        .collect();
    table(&properties, &[3000], &rows)
}

/// A table of one cell 9000 twips wide that holds `blocks`, and then the paragraph "z".
fn in_a_cell(blocks: &str) -> String {
    let outer = table(
        r#"<w:tblW w:w="9000" w:type="dxa"/>"#,
        &[9000],
        &[("", &[blocks])],
    );
    outer + &p("z")
}

const RIGHT: &str = r#" w:tblpXSpec="right""#;

#[test]
fn puts_two_floating_tables_of_a_cell_side_by_side() {
    // The second table stands at the cell's right edge on the baseline of the first, and the
    // row is as tall as with the first table alone.
    let both = floating("", &["l"]) + &floating(RIGHT, &["r"]) + &p("");
    let list = lay_out(&in_a_cell(&both), NORMAL, None);
    let (l, r) = (find(&list, 'l'), find(&list, 'r'));
    assert_eq!(l.2, r.2);
    assert!(r.1 - l.1 > 5000 * Length::UNITS_PER_TWIP);
    let alone = floating("", &["l"]) + &p("");
    let one = lay_out(&in_a_cell(&alone), NORMAL, None);
    assert_eq!(find(&list, 'z'), find(&one, 'z'));
    // An alignment down does nothing for a table that hangs on the text.
    let centered = floating("", &["l", "m", "n"])
        + &floating(r#" w:tblpXSpec="right" w:tblpYSpec="center""#, &["r"])
        + &p("");
    let list = lay_out(&in_a_cell(&centered), NORMAL, None);
    assert_eq!(find(&list, 'l').2, find(&list, 'r').2);
}

#[test]
fn floats_a_table_of_a_cell_that_hangs_on_the_text_down_whatever_its_anchor_across() {
    // Across from the margin or the page, the table stands where its twin across from the text
    // stands: offset from the cell's text column, with the paragraph beside it.
    let blocks = |across: &str| {
        p("a") + &floating(&format!(r#"{across} w:tblpX="1440" w:tblpY="200""#), &["l"]) + &p("b")
    };
    let text = lay_out(&in_a_cell(&blocks("")), NORMAL, None);
    let (l, b) = (find(&text, 'l'), find(&text, 'b'));
    assert!(b.1 < l.1);
    for across in [r#" w:horzAnchor="margin""#, r#" w:horzAnchor="page""#] {
        let list = lay_out(&in_a_cell(&blocks(across)), NORMAL, None);
        assert_eq!(find(&list, 'l'), l, "{across}");
        assert_eq!(find(&list, 'b'), b, "{across}");
    }
    // With a negative offset down it stays in the flow, below the paragraph before it.
    let raised = p("a") + &floating(r#" w:horzAnchor="margin" w:tblpY="-165""#, &["l"]) + &p("b");
    let list = lay_out(&in_a_cell(&raised), NORMAL, None);
    let (a, l, b) = (find(&list, 'a'), find(&list, 'l'), find(&list, 'b'));
    assert!(a.2 < l.2 && l.2 < b.2);
}

#[test]
fn lays_out_a_table_of_a_cell_without_room_beside_it_as_a_table_in_the_flow() {
    // A page holds 64 lines. The row cannot split but is taller than the page, so it splits:
    // its first cell has 150 lines and its second 80, then a table as wide as the cell that
    // hangs on the text, and "b". The table leaves no room beside it, so it stays in the flow
    // of the cell and breaks between the row's parts as the same table without `w:tblpPr`.
    let inner = |placement: &str| {
        let rows: Vec<String> = (0..20).map(|_| p("l")).collect();
        let rows: Vec<(&str, [&str; 1])> = rows.iter().map(|cell| ("", [cell.as_str()])).collect();
        let rows: Vec<(&str, &[&str])> = rows
            .iter()
            .map(|(props, cell)| (*props, &cell[..]))
            .collect();
        table(
            &format!(r#"{placement}<w:tblW w:w="6000" w:type="dxa"/>"#),
            &[6000],
            &rows,
        )
    };
    let lay = |placement: &str| {
        let second = filler(80) + &inner(placement) + &p("b");
        let rows: &[(&str, &[&str])] = &[("<w:cantSplit/>", &[&(filler(149) + &p("a")), &second])];
        let body = table(r#"<w:tblW w:w="9360" w:type="dxa"/>"#, &[3000, 6360], rows);
        let target = on_base_with(|p| p.with_variant(FloatingTableBreaks::AcrossPages));
        pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list
    };
    let flow = lay("");
    let placed = lay(r#"<w:tblpPr w:vertAnchor="text" w:horzAnchor="margin" w:tblpY="0"/>"#);
    assert_eq!(placed.pages().len(), flow.pages().len());
    assert_eq!(find(&placed, 'a'), find(&flow, 'a'));
    assert_eq!(find(&placed, 'b'), find(&flow, 'b'));
    assert_eq!(find_all(&placed, 'l'), find_all(&flow, 'l'));
}

#[test]
fn flows_the_text_of_a_cell_beside_its_floating_table_and_grows_the_row() {
    // The paragraph starts on the baseline of the table's first row, right of the table, and
    // the row holds the three rows of the table.
    let blocks = floating("", &["l", "m", "n"]) + &p("b");
    let list = lay_out(&in_a_cell(&blocks), NORMAL, None);
    let (l, n, b, z) = (
        find(&list, 'l'),
        find(&list, 'n'),
        find(&list, 'b'),
        find(&list, 'z'),
    );
    assert_eq!(l.2, b.2);
    assert!(b.1 - l.1 >= 2800 * Length::UNITS_PER_TWIP);
    assert!(z.2 > n.2);
    // A table as wide as the cell stays in the flow, and the paragraph stands below it.
    let wide = table(
        r#"<w:tblpPr w:vertAnchor="text"/><w:tblW w:w="9000" w:type="dxa"/>"#,
        &[9000],
        &[("", &[&p("l")])],
    );
    let list = lay_out(&in_a_cell(&(wide + &p("b"))), NORMAL, None);
    assert!(find(&list, 'b').2 > find(&list, 'l').2);
}

#[test]
fn joins_floating_tables_with_the_same_properties_into_one_table() {
    // Two floating tables that follow each other directly: the second goes on below the
    // first as its next row, in a cell and in the body.
    let two = floating("", &["l"]) + &floating("", &["r"]) + &p("");
    let one = floating("", &["l", "r"]) + &p("");
    for wrap in [in_a_cell, |blocks: &str| blocks.to_owned() + &p("z")] {
        let list = lay_out(&wrap(&two), NORMAL, None);
        let joined = lay_out(&wrap(&one), NORMAL, None);
        for ch in ['l', 'r', 'z'] {
            assert_eq!(find_all(&list, ch), find_all(&joined, ch));
        }
        assert!(find(&list, 'r').2 > find(&list, 'l').2);
    }
    // A table with another placement does not go on the first one.
    let apart = floating("", &["l"]) + &floating(RIGHT, &["r"]) + &p("");
    let list = lay_out(&apart, NORMAL, None);
    assert_eq!(find(&list, 'l').2, find(&list, 'r').2);
}

/// The paragraph "a" with 10 pt after.
fn spaced_a() -> String {
    r#"<w:p><w:pPr><w:spacing w:before="0" w:after="200"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#
        .to_owned()
}

#[test]
fn keeps_the_bottom_distance_below_a_table_on_the_text_without_room_beside_it() {
    // A table as wide as the text stays in the flow, and the paragraph after it starts
    // `w:bottomFromText` below its bottom, where a space before of that size would put it, to
    // a device unit.
    let lay = |bottom: u32, after: &str| {
        let wide = table(
            &format!(
                r#"<w:tblpPr w:bottomFromText="{bottom}" w:vertAnchor="text"/><w:tblW w:w="9360" w:type="dxa"/>"#
            ),
            &[9360],
            &[("", &[&p("l")])],
        );
        find(&lay_out(&(p("t") + &wide + after), NORMAL, None), 'b')
    };
    let spaced_b =
        r#"<w:p><w:pPr><w:spacing w:before="200"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
    let (kept, spaced) = (lay(200, &p("b")), lay(0, spaced_b));
    assert!(kept.2.abs_diff(spaced.2) <= 1, "{kept:?} {spaced:?}");
    assert!(kept.2 > lay(0, &p("b")).2);
}

#[test]
fn keeps_the_space_after_the_paragraph_before_a_table_with_room_beside_it() {
    // Beside a narrow floating table, the paragraph after it starts below the space after of
    // the paragraph before the table, as without the table.
    let with_table = lay_out(
        &(spaced_a() + &floating("", &["l"]) + &p("b")),
        NORMAL,
        None,
    );
    let without = lay_out(&(spaced_a() + &p("b")), NORMAL, None);
    assert_eq!(find(&with_table, 'b').2, find(&without, 'b').2);
}