use std::fmt::Write as _;
use super::{SECTION, docx, lines, render};
use crate::test_fonts::{CARLITO_RUN, carlito};
fn text(text: &str) -> String {
format!(r#"<w:r>{CARLITO_RUN}<w:t xml:space="preserve">{text}</w:t></w:r>"#)
}
fn reference(kind: &str, id: u32) -> String {
format!(r#"<w:r>{CARLITO_RUN}<w:{kind}Reference w:id="{id}"/></w:r>"#)
}
fn notes(kind: &str, count: u32) -> String {
let mut part = format!(
r#"<w:{kind} w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:{kind}>"#
);
for id in 1..=count {
write!(
part,
r#"<w:{kind} w:id="{id}"><w:p><w:r>{CARLITO_RUN}<w:{kind}Ref/></w:r>{}</w:p></w:{kind}>"#,
text(&format!(" Note{id}"))
)
.unwrap();
}
part
}
fn pages(body: &str, settings: &str, (footnotes, endnotes): (u32, u32)) -> Vec<Vec<String>> {
let parts = [
("n1", notes("footnote", footnotes)),
("e1", notes("endnote", endnotes)),
];
let parts: Vec<(&str, &str)> = parts.iter().map(|(id, xml)| (*id, xml.as_str())).collect();
lines(&render(&docx(body, &parts, settings)))
.iter()
.map(|page| page.iter().map(|(_, text)| text.clone()).collect())
.collect()
}
fn sections(runs: &[String], notes: &[&str]) -> String {
assert_eq!(runs.len(), notes.len());
let mut body = String::new();
for (index, (paragraph, notes)) in runs.iter().zip(notes).enumerate() {
if index + 1 < runs.len() {
write!(
body,
"<w:p><w:pPr><w:sectPr>{notes}{SECTION}</w:sectPr></w:pPr>{paragraph}</w:p>"
)
} else {
write!(
body,
"<w:p>{paragraph}</w:p><w:sectPr>{notes}{SECTION}</w:sectPr>"
)
}
.unwrap();
}
body
}
#[test]
fn numbers_footnotes_in_the_format_and_from_the_start_of_their_section() {
let body = |notes: &str| {
format!(
"<w:p>{}{}{}{}</w:p><w:sectPr>{SECTION}{notes}</w:sectPr>",
text("A"),
reference("footnote", 1),
text("B"),
reference("footnote", 2)
)
};
let settings =
r#"<w:footnotePr><w:numFmt w:val="decimal"/><w:numStart w:val="5"/></w:footnotePr>"#;
let own = r#"<w:footnotePr><w:numFmt w:val="lowerRoman"/></w:footnotePr>"#;
assert_eq!(
pages(&body(own), settings, (2, 0)),
[["AvBvi", "v Note1", "vi Note2"]]
);
assert_eq!(
pages(&body(""), settings, (2, 0)),
[["A5B6", "5 Note1", "6 Note2"]]
);
assert_eq!(
pages(&body(""), "", (2, 0)),
[["A1B2", "1 Note1", "2 Note2"]]
);
}
#[test]
fn starts_footnote_numbers_again_in_a_section_that_restarts_them() {
let paragraphs = [
text("A") + &reference("footnote", 1),
text("B") + &reference("footnote", 2),
];
let restart = r#"<w:footnotePr><w:numRestart w:val="eachSect"/></w:footnotePr>"#;
assert_eq!(
pages(§ions(¶graphs, &["", restart]), "", (2, 0)),
[["A1", "1 Note1"], ["B1", "1 Note2"]]
);
assert_eq!(
pages(§ions(¶graphs, &["", ""]), "", (2, 0)),
[["A1", "1 Note1"], ["B2", "2 Note2"]]
);
}
#[test]
fn starts_footnote_numbers_again_on_each_page_by_the_pages_of_the_pass_before() {
let mut lines = vec![format!("{}{}", text("L1"), reference("footnote", 1))];
for number in 2..=13 {
lines.push(text(&format!("L{number}")));
}
lines.push(format!("{}{}", text("Z"), reference("footnote", 2)));
let body = format!(
"<w:p>{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
lines.join("<w:r><w:br/></w:r>")
);
let restart = r#"<w:footnotePr><w:numRestart w:val="eachPage"/></w:footnotePr>"#;
let last_page = |settings: &str| {
let pages = pages(&body, settings, (2, 0));
assert_eq!(pages.len(), 2, "{pages:?}");
pages[1].clone()
};
let restarted = last_page(restart);
assert!(restarted.contains(&"Z1".to_owned()), "{restarted:?}");
assert!(restarted.contains(&"1 Note2".to_owned()), "{restarted:?}");
let continued = last_page("");
assert!(continued.contains(&"Z2".to_owned()), "{continued:?}");
assert!(continued.contains(&"2 Note2".to_owned()), "{continued:?}");
}
#[test]
fn numbers_footnotes_on_after_pages_that_restart_them_by_every_footnote_before() {
let paragraphs = [
text("A") + &reference("footnote", 1),
text("B") + &reference("footnote", 2),
text("C") + &reference("footnote", 3),
];
let restart = r#"<w:footnotePr><w:numRestart w:val="eachPage"/></w:footnotePr>"#;
assert_eq!(
pages(§ions(¶graphs, &[restart, restart, ""]), "", (3, 0)),
[["A1", "1 Note1"], ["B1", "1 Note2"], ["C3", "3 Note3"]]
);
}
#[test]
fn numbers_endnotes_as_the_section_of_their_reference_asks() {
let paragraphs = [
text("A") + &reference("endnote", 1),
text("B") + &reference("endnote", 2),
];
let own =
r#"<w:endnotePr><w:numFmt w:val="decimal"/><w:numRestart w:val="eachSect"/></w:endnotePr>"#;
assert_eq!(
pages(§ions(¶graphs, &["", own]), "", (0, 2)),
[vec!["Ai"], vec!["B1", "i Note1", "1 Note2"]]
);
let own = r#"<w:endnotePr><w:numFmt w:val="decimal"/></w:endnotePr>"#;
assert_eq!(
pages(§ions(¶graphs, &["", own]), "", (0, 2)),
[vec!["Ai"], vec!["B2", "i Note1", "2 Note2"]]
);
}
fn opened_with_notes(
kind: &str,
reference: &str,
notes: &[(&str, &str)],
) -> crate::Warned<crate::Document> {
let body = format!(
r#"<w:p>{}<w:r>{CARLITO_RUN}<w:{kind}Reference w:id="{reference}"/></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#,
text("A")
);
let mut part = format!(
r#"<w:{kind} w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:{kind}>"#
);
for (id, shown) in notes {
write!(
part,
r#"<w:{kind} w:id="{id}"><w:p><w:r>{CARLITO_RUN}<w:{kind}Ref/></w:r>{}</w:p></w:{kind}>"#,
text(shown)
)
.unwrap();
}
let name = if kind == "footnote" { "n1" } else { "e1" };
crate::Document::open(
&docx(&body, &[(name, &part)], ""),
&carlito(),
&crate::Options::base(),
)
.unwrap()
}
fn page_texts(document: &crate::Document) -> Vec<Vec<String>> {
lines(document.display_list())
.iter()
.map(|page| page.iter().map(|(_, text)| text.clone()).collect())
.collect()
}
fn with_ids(kind: &str, reference: &str, id: &str) -> (Vec<Vec<String>>, Vec<String>) {
use crate::docx::{ValuePlace, Warning as DocxWarning};
let opened = opened_with_notes(kind, reference, &[(id, " Note")]);
let pages = page_texts(&opened.value);
let invalid = opened
.warnings
.iter()
.filter_map(|(warning, _)| match warning {
crate::Warning::Docx(DocxWarning::InvalidValue {
part,
element,
place,
..
}) => Some(format!(
"{} {} {}",
part.as_str(),
element.as_str(),
match place {
ValuePlace::Attribute(attribute) => attribute.as_str().to_owned(),
other => other.to_string(),
}
)),
_ => None,
})
.collect();
(pages, invalid)
}
#[test]
fn finds_a_note_by_the_number_of_its_id() {
let found = |kind| with_ids(kind, "01", "1");
assert_eq!(
found("footnote"),
(vec![vec!["A1".to_owned(), "1 Note".to_owned()]], vec![])
);
let endnote = with_ids("endnote", "+1", "1.0");
assert_eq!(
endnote,
(vec![vec!["Ai".to_owned(), "i Note".to_owned()]], vec![])
);
}
#[test]
fn shows_no_number_for_a_reference_whose_id_does_not_read() {
let (pages, invalid) = with_ids("footnote", "x", "1");
assert_eq!(pages, [vec!["A"]]);
assert_eq!(invalid, ["word/document.xml footnoteReference id"]);
let (pages, invalid) = with_ids("endnote", "x", "1");
assert_eq!(pages, [vec!["A"]]);
assert_eq!(invalid, ["word/document.xml endnoteReference id"]);
}
#[test]
fn keeps_no_note_whose_id_does_not_read() {
let (pages, invalid) = with_ids("footnote", "1", "1x");
assert_eq!(pages, [vec!["A1"]]);
assert_eq!(invalid, ["word/n1.xml footnote id"]);
let (pages, invalid) = with_ids("endnote", "1", "1x");
assert_eq!(pages, [vec!["Ai"]]);
assert_eq!(invalid, ["word/e1.xml endnote id"]);
}
#[test]
fn keeps_and_finds_a_normal_note_whose_id_is_negative() {
let (pages, invalid) = with_ids("footnote", "-03", "-3");
assert_eq!(pages, [vec!["A1", "1 Note"]]);
assert_eq!(invalid, Vec::<String>::new());
}
#[test]
fn keeps_the_last_note_of_one_number_and_warns_of_each_one_that_replaces_another() {
use crate::docx::Warning as DocxWarning;
let notes = [
("1", " Early"),
("01", " Late"),
("2", " Other"),
("1.0", " Last"),
("-1", " Minus"),
];
for (kind, name, label) in [
("footnote", "word/n1.xml", "1"),
("endnote", "word/e1.xml", "i"),
] {
let opened = opened_with_notes(kind, "1", ¬es);
assert_eq!(
page_texts(&opened.value),
[vec![format!("A{label}"), format!("{label} Last")]]
);
let repeated: Vec<_> = opened
.warnings
.iter()
.filter_map(|(warning, count)| match warning {
crate::Warning::Docx(DocxWarning::NoteIdRepeated { part, id }) => {
Some((part.as_str().to_owned(), *id, count))
}
_ => None,
})
.collect();
assert_eq!(repeated, [(name.to_owned(), 1, 2)]);
}
}
fn missing_notes(
opened: &crate::Warned<crate::Document>,
) -> Vec<(String, crate::docx::NoteKind, i64, u32)> {
opened
.warnings
.iter()
.filter_map(|(warning, count)| match warning {
crate::Warning::Docx(crate::docx::Warning::NoteMissing { part, note, id }) => {
Some((part.as_str().to_owned(), *note, *id, count))
}
_ => None,
})
.collect()
}
#[test]
fn warns_of_a_reference_to_a_note_that_the_notes_part_does_not_have() {
use crate::docx::NoteKind;
for (kind, note, label) in [
("footnote", NoteKind::Footnote, "1"),
("endnote", NoteKind::Endnote, "i"),
] {
let opened = opened_with_notes(kind, "2", &[("1", " Note")]);
assert_eq!(page_texts(&opened.value)[0][0], format!("A{label}"));
assert_eq!(
missing_notes(&opened),
[("word/document.xml".to_owned(), note, 2, 1)]
);
let opened = opened_with_notes(kind, "1", &[("1", " Note")]);
assert_eq!(missing_notes(&opened), []);
}
}