f-office-docx 0.2.3

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);
}

fn anchored_drawing(x_emu: i64, w_emu: i64, h_emu: i64, dist_b_emu: i64, wrap: &str) -> String {
    use crate::ns::{A, WP, WPS};
    format!(
        r#"<w:p><w:r><w:drawing><wp:anchor xmlns:wp="{WP}" distT="0" distB="{dist_b_emu}" distL="114300" distR="114300" simplePos="0" relativeHeight="1" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="margin"><wp:posOffset>{x_emu}</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="{w_emu}" cy="{h_emu}"/><wp:effectExtent l="0" t="0" r="0" b="0"/>{wrap}<wp:docPr id="1" name="B"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r><w:r><w:t>a</w:t></w:r></w:p>"#
    )
}

#[test]
fn inline_table_clears_or_wraps_beside_floating_drawings() {
    let sq = r#"<wp:wrapSquare wrapText="bothSides"/>"#;
    let none = "<wp:wrapNone/>";
    let wide_tbl = table("", &[9360], &[("", &[&p("t")])]);
    let narrow_tbl = table("", &[4000], &[("", &[&p("t")])]);

    // 1. Wide inline table overlapping a 40 pt wrapSquare box moves down below the box (+ distB).
    let base_none = lay_out(
        &(anchored_drawing(0, 1_524_000, 508_000, 0, none) + &wide_tbl),
        NORMAL,
        None,
    );
    let below_sq = lay_out(
        &(anchored_drawing(0, 1_524_000, 508_000, 0, sq) + &wide_tbl),
        NORMAL,
        None,
    );
    let below_sq_db = lay_out(
        &(anchored_drawing(0, 1_524_000, 508_000, 127_000, sq) + &wide_tbl),
        NORMAL,
        None,
    );
    let t_none = find(&base_none, 't');
    let t_sq = find(&below_sq, 't');
    let t_sq_db = find(&below_sq_db, 't');
    // 40 pt box vs 10 pt anchor line pushes table down 30 pt (~125 dots); +10 pt distB adds ~42 dots.
    assert_eq!(t_sq.1, t_none.1);
    assert!(
        (t_sq.2 - t_none.2 - 125).abs() <= 1,
        "{t_sq:?} vs {t_none:?}"
    );
    assert!(
        (t_sq_db.2 - t_sq.2 - 42).abs() <= 1,
        "{t_sq_db:?} vs {t_sq:?}"
    );

    // 2. Narrow inline table (200 pt) on the left does NOT move for a right-side wrapSquare box.
    let right_sq = lay_out(
        &(anchored_drawing(4_318_000, 1_524_000, 508_000, 0, sq) + &narrow_tbl),
        NORMAL,
        None,
    );
    let narrow_none = lay_out(
        &(anchored_drawing(0, 1_524_000, 508_000, 0, none) + &narrow_tbl),
        NORMAL,
        None,
    );
    assert_eq!(find(&right_sq, 't'), find(&narrow_none, 't'));

    // 3. Narrow inline table (200 pt) overlapping a left-side 120 pt wrapSquare box shifts right
    //    beside the box (same y, x shifted by 120 + 9 = 129 pt).
    let beside = lay_out(
        &(anchored_drawing(0, 1_524_000, 508_000, 0, sq) + &narrow_tbl),
        NORMAL,
        None,
    );
    let t_beside = find(&beside, 't');
    let t_narrow = find(&narrow_none, 't');
    assert_eq!(t_beside.2, t_narrow.2);
    assert!(t_beside.1 > t_narrow.1, "{t_beside:?} vs {t_narrow:?}");

    // 4. A wrap wholly in the left margin does not push a table with negative tblInd down.
    let neg_ind = table(
        r#"<w:tblInd w:w="-120" w:type="dxa"/>"#,
        &[9360],
        &[("", &[&p("t")])],
    );
    let margin_sq = lay_out(
        &(anchored_drawing(-635_000, 495_300, 508_000, 0, sq) + &neg_ind),
        NORMAL,
        None,
    );
    let margin_none = lay_out(
        &(anchored_drawing(-635_000, 495_300, 508_000, 0, none) + &neg_ind),
        NORMAL,
        None,
    );
    assert_eq!(find(&margin_sq, 't'), find(&margin_none, 't'));
}

#[test]
fn inline_table_clears_right_wraps_and_polygon_bounds() {
    let sq = r#"<wp:wrapSquare wrapText="bothSides"/>"#;
    let none = "<wp:wrapNone/>";
    let wide_tbl = table("", &[9360], &[("", &[&p("t")])]);

    // Right-aligned narrow table beside a right-side wrap stays at the same y inside [col_left, sq.left].
    let right_tbl = table(r#"<w:jc w:val="right"/>"#, &[4000], &[("", &[&p("t")])]);
    let rgt_sq = lay_out(
        &(anchored_drawing(4_318_000, 1_524_000, 508_000, 0, sq) + &right_tbl),
        NORMAL,
        None,
    );
    let rgt_none = lay_out(
        &(anchored_drawing(0, 1_524_000, 508_000, 0, none) + &right_tbl),
        NORMAL,
        None,
    );
    let t_rgt_sq = find(&rgt_sq, 't');
    let t_rgt_none = find(&rgt_none, 't');
    assert_eq!(t_rgt_sq.2, t_rgt_none.2);
    assert!(t_rgt_sq.1 < t_rgt_none.1, "{t_rgt_sq:?} vs {t_rgt_none:?}");

    // A wrapTight half-height polygon (0..30 pt inside a 120 pt box) does not push a table
    // starting below the polygon's bottom down to the box's bottom.
    let half_poly = r#"<wp:wrapTight wrapText="bothSides"><wp:wrapPolygon edited="0"><wp:start x="0" y="0"/><wp:lineTo x="0" y="5400"/><wp:lineTo x="21600" y="5400"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/></wp:wrapPolygon></wp:wrapTight>"#;
    let body_poly =
        anchored_drawing(0, 1_524_000, 1_524_000, 0, half_poly) + &p("b") + &p("c") + &wide_tbl;
    let body_ctrl =
        anchored_drawing(0, 1_524_000, 1_524_000, 0, none) + &p("b") + &p("c") + &wide_tbl;
    let t_poly = find(&lay_out(&body_poly, NORMAL, None), 't');
    let t_ctrl = find(&lay_out(&body_ctrl, NORMAL, None), 't');
    assert_eq!(t_poly.2, t_ctrl.2);
}