Files
docx/scripts/compare-layout.ts
T
DolanandClaude Opus 5.5 3f5a17cd10 feat(layout): break table rows across pages, lay out footnotes and columns, and write the numbers of pages (#3592)
* feat(layout): break table rows across pages between the lines of their cells

Word and LibreOffice break a table row that doesn't fit across the pages
unless it is kept whole (cantSplit), but the layout moved every row to the
next page whole, which put the headings after a table of long rows on the
wrong page. Rows now break between the lines of their cells, with the
header rows repeated above the rest, and without widow control inside
them, as LibreOffice does. Rows kept whole, of an exact height, or whose
text fits but not their set height, still move whole. A row that would
break with merged cells, a table in it, or a height set taller than its
text stops the layout, as nothing checks how those break yet.

LibreOffice's lines are whole twips tall, so lines are rounded to twips:
that matches its line pitch for 80 of 90 font sizes measured, against none
before. The tables demo is at 12 points, as LibreOffice's lines of Times
New Roman at 10 points are a twip taller than the font's metrics.

A new layout demo, tables-across-pages, has rows of each kind across page
breaks. All 185 headings of the 7 demos are on LibreOffice's page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* feat(layout): lay out footnotes at the bottom of their pages, and endnotes after the text

The layout stopped at the first footnote, so most reports lost every page
number after it. Now a page's footnotes take room at its bottom, below
their separator, with the space between them, but not before the
separator or after the last, as LibreOffice lays them out. A line whose
one-line footnote doesn't fit below it moves to the next page with it, as
in LibreOffice. LibreOffice continues a longer footnote on the next page,
splitting even one widow control would keep together, and which of its
lines stay isn't followed yet, so the layout stops there, and at a
footnote in a table row that breaks across pages.

Endnotes follow the text, after their separator, as Word and LibreOffice
lay them out. Footnotes are numbered 1, 2, 3 and endnotes i, ii, iii, and
their numbers are as narrow as superscript and as tall as their font.

A new layout demo, footnotes-and-endnotes, has 40 footnotes over 8 pages.
All 18 of its headings are on LibreOffice's page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* feat(layout): lay out sections in columns

The layout stopped at the first section in columns. Now each page's
columns are filled in turn, each as wide as the section gives, before the
next page: text moves to the next column when it doesn't fit, or is kept
with what is there, and a column break starts the next column, or a new
page in the last. A section in columns that starts on the same page as
the text before it starts its columns below that text.

Word and LibreOffice even out a section's columns before a continuous
section break, so the next section starts below the longest, and which
lines go in which column isn't followed yet, so the layout stops there,
as it does at a footnote in columns and at a table's header rows repeated
at the top of a column.

scripts/compare-layout.sh reads LibreOffice's text in reading order, so a
page's columns come one after the other rather than side by side. A new
layout demo, columns, has sections of one, two and three columns. All 227
headings of the 9 demos are on LibreOffice's page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* feat(layout): write the numbers of pages into NUMPAGES and SECTIONPAGES fields

paginate counted the pages, but nothing wrote the count, so "Page 3 of"
footers were written without their number, which applications that show
fields as they are written show blank. Now docx/layout works out the
number of pages of the document, when it lays all of it out, and of each
section whose pages are its own, laying the pages out again until the
numbers, which can change how lines wrap, stay the same.

EstimatedPageNumbers gains pageCount and sectionPageCounts, and docx
writes them into the NUMPAGES and SECTIONPAGES fields of the body, and
of the headers and footers once the body is written, with the page
references in them. A header or footer shows the number of pages of the
sections it is on only when they all have the same. A section that
shares a page with another, or has a blank page before or after it, is
left blank, as is a field in a number format of its own. Like PAGEREF
fields, those with a numeric picture (\#) are left as they are.

scripts/compare-layout.ts checks the numbers of pages written into the
demos against the pages of LibreOffice's PDFs: both demos with them match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* fix(layout): keep a paragraph with the next on a new page when they fit there

Whether what is kept together fits in a fresh column was measured from
where the page's columns start, which is partway down the page below a
continuous section break. When the column is the last, the kept
paragraphs go on a new page, whose text starts at the top, so a heading
that would fit there with the next paragraph stayed at the bottom of the
page, and the paragraph moved on alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* fix(layout): stop at a section whose columns differ in width

A paragraph is broken into lines at the width of the column it starts
in, and a paragraph that goes on into a column of another width kept
those lines, so its height, and the pages after it, were wrong. Breaking
the rest of a paragraph again needs to know where each line starts in
its text, so a section with columns of different widths stops the
layout, and the page numbers after it are left blank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* fix: fail the layout comparison when LibreOffice didn't lay out a document

The comparison skipped a document without the text of LibreOffice's
pages, as when LibreOffice fails to convert it, and reported its
headings as matching, so CI could pass without comparing it. Now it
fails, and names the documents LibreOffice didn't lay out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:50:47 +01:00

171 lines
8.1 KiB
TypeScript

/**
* Compares the page numbers docx/layout wrote into the tables of contents of the documents scripts/compare-layout.sh
* made with the pages LibreOffice put their headings on, and Word, when PDFs of them saved from Word are there.
*
* Usage: npm run run-ts -- scripts/compare-layout.ts [directory]
*
* The directory (default build/layout) has each document's .docx, and the text of LibreOffice's pages of it in a .txt,
* with the pages split by form feeds, as pdftotext writes them, and of Word's in a .word.txt. A heading is on the last
* page with a line of only its text, as its entry in the table of contents, before it, has its page number on the line
* too. Spaces and tabs count as one space, because pdftotext can write a tab, or a wide gap, as several. So the headings
* of the documents compared are each on a line of their own, and their pages are numbered from 1. It fails when a
* heading's page number isn't LibreOffice's or Word's, or is left blank, when the number of pages written into a NUMPAGES
* field isn't the number of pages of LibreOffice's or Word's PDF, and when there is no text of LibreOffice's pages of a
* document, as when it couldn't convert it.
*/
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import JSZip from "jszip";
import { type Element, xml2js } from "xml-js";
const directory = process.argv[2] ?? "build/layout";
/** The text of an element, with its tabs, leaving out field instructions */
const textOf = (element: Element): string => {
if (element.type === "text") {
return String(element.text);
}
if (element.name === "w:instrText") {
return "";
}
if (element.name === "w:tab" && element.type === "element") {
return "\t";
}
return (element.elements ?? []).map(textOf).join("");
};
/** Text with each run of spaces and tabs as one space, and none at either end */
const collapsed = (text: string): string => text.replace(/\s+/g, " ").trim();
const paragraphsIn = (element: Element): readonly Element[] =>
element.name === "w:p" ? [element] : (element.elements ?? []).flatMap(paragraphsIn);
/** Each entry of the document's tables of contents: its heading's text, and the page number written for it */
const entriesOf = async (path: string): Promise<readonly { readonly title: string; readonly page: string }[]> => {
const zip = await JSZip.loadAsync(readFileSync(path));
const document = xml2js(await zip.file("word/document.xml")!.async("string"), { compact: false }) as Element;
return paragraphsIn(document)
.filter((paragraph) => JSON.stringify(paragraph).includes("PAGEREF _Toc"))
.map((paragraph) => {
// Leaving out the paragraph's properties, whose tab stops aren't tabs in its text
const text = (paragraph.elements ?? [])
.filter(({ name }) => name !== "w:pPr")
.map(textOf)
.join("");
const split = text.lastIndexOf("\t");
return { title: collapsed(text.slice(0, split)), page: text.slice(split + 1).trim() };
});
};
/** The results written into the NUMPAGES fields of the document's text, headers and footers */
const pageCountsOf = async (path: string): Promise<readonly string[]> => {
const zip = await JSZip.loadAsync(readFileSync(path));
const parts = Object.keys(zip.files).filter((file) => /^word\/(document|header\d+|footer\d+)\.xml$/.test(file));
const results: string[] = [];
const fields: { instruction: string; result?: string }[] = [];
const read = (element: Element): void => {
const field = fields[fields.length - 1];
const type = element.name === "w:fldChar" ? element.attributes?.["w:fldCharType"] : undefined;
if (type === "begin") {
fields.push({ instruction: "" });
} else if (type === "separate" && field) {
field.result = "";
} else if (type === "end" && field) {
fields.pop();
if (/^\s*NUMPAGES\b/.test(field.instruction)) {
results.push(field.result ?? "");
}
} else if (element.name === "w:instrText" && field) {
field.instruction += textOf({ ...element, name: "w:t" });
} else if (element.name === "w:t" && field?.result !== undefined) {
field.result += textOf(element);
} else {
(element.elements ?? []).forEach(read);
}
};
for (const part of parts) {
read(xml2js(await zip.file(part)!.async("string"), { compact: false }) as Element);
}
return results;
};
/** The pages of a PDF's text, each as its lines, or undefined when there is no such file */
const pagesOf = (path: string): readonly (readonly string[])[] | undefined =>
existsSync(path)
? readFileSync(path, "utf8")
.split("\f")
.map((page) => page.split("\n").map(collapsed))
: undefined;
// What each document is compared with: LibreOffice's pages, and Word's when they are there (see scripts/compare-layout.sh)
const REFERENCES = [
{ name: "LibreOffice", suffix: ".txt" },
{ name: "Word", suffix: ".word.txt" },
] as const;
const counts = new Map(REFERENCES.map(({ name }) => [name, { compared: 0, matched: 0 }]));
const pageCounts = new Map(REFERENCES.map(({ name }) => [name, { compared: 0, matched: 0 }]));
// The documents LibreOffice didn't lay out, which aren't compared
const notLaidOut: string[] = [];
for (const name of readdirSync(directory)
.filter((file) => file.endsWith(".docx"))
.sort()) {
const entries = await entriesOf(join(directory, name));
const references = REFERENCES.flatMap((reference) => {
const pages = pagesOf(join(directory, name.replace(/\.docx$/, reference.suffix)));
return pages ? [{ ...reference, pages }] : [];
});
console.log(`\n${name}`);
if (!references.some((reference) => reference.name === "LibreOffice")) {
console.log(" FAIL LibreOffice didn't lay it out");
notLaidOut.push(name);
}
for (const { title, page } of entries) {
const results = references.map(({ name: reference, pages }) => {
const found = String(pages.findLastIndex((lines) => lines.includes(title)) + 1);
const count = counts.get(reference)!;
count.compared++;
count.matched += page === found ? 1 : 0;
return `${page === found ? " " : "*"}${reference} ${found === "0" ? "none" : found.padStart(4)}`;
});
const matches = results.every((result) => result.startsWith(" "));
console.log(
`${matches ? " ok " : " FAIL"} ${title.padEnd(50)} docx/layout ${(page || "blank").padStart(5)} ${results.join(" ")}`,
);
}
// pdftotext ends each page with a form feed
const written = [...new Set(await pageCountsOf(join(directory, name)))];
if (written.length > 0) {
const results = references.map(({ name: reference, pages }) => {
const found = String(pages.length - 1);
const count = pageCounts.get(reference)!;
count.compared++;
count.matched += written.length === 1 && written[0] === found ? 1 : 0;
return `${written.length === 1 && written[0] === found ? " " : "*"}${reference} ${found.padStart(4)}`;
});
const matches = results.every((result) => result.startsWith(" "));
console.log(
`${matches ? " ok " : " FAIL"} ${"Number of pages (NUMPAGES)".padEnd(50)} docx/layout ${(written.join(", ") || "blank").padStart(5)} ${results.join(" ")}`,
);
}
}
console.log("");
for (const [reference, { compared, matched }] of counts) {
if (compared > 0) {
console.log(`${matched} of ${compared} headings are on ${reference}'s page`);
}
}
for (const [reference, { compared, matched }] of pageCounts) {
if (compared > 0) {
console.log(`${matched} of ${compared} numbers of pages are ${reference}'s`);
}
}
if (notLaidOut.length > 0) {
console.log(`LibreOffice didn't lay out ${notLaidOut.join(", ")}`);
}
process.exit(
notLaidOut.length === 0 && [...counts.values(), ...pageCounts.values()].every(({ compared, matched }) => compared === matched) ? 0 : 1,
);