paged-react 0.2.6 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -7
- package/dist/components/context.d.ts +4 -0
- package/dist/components/context.d.ts.map +1 -0
- package/dist/components/context.js +3 -0
- package/dist/components/context.js.map +1 -0
- package/dist/components/document.d.ts +7 -2
- package/dist/components/document.d.ts.map +1 -1
- package/dist/components/document.js +6 -6
- package/dist/components/document.js.map +1 -1
- package/dist/components/page-number.d.ts +19 -2
- package/dist/components/page-number.d.ts.map +1 -1
- package/dist/components/page-number.js +11 -4
- package/dist/components/page-number.js.map +1 -1
- package/dist/core/avoid-break.d.ts +2 -0
- package/dist/core/avoid-break.d.ts.map +1 -1
- package/dist/core/avoid-break.js +22 -9
- package/dist/core/avoid-break.js.map +1 -1
- package/dist/core/computed-style.d.ts +2 -0
- package/dist/core/computed-style.d.ts.map +1 -1
- package/dist/core/computed-style.js +4 -0
- package/dist/core/computed-style.js.map +1 -1
- package/dist/core/ir-extract.d.ts +5 -0
- package/dist/core/ir-extract.d.ts.map +1 -0
- package/dist/core/ir-extract.js +152 -0
- package/dist/core/ir-extract.js.map +1 -0
- package/dist/core/ir-style.d.ts +9 -0
- package/dist/core/ir-style.d.ts.map +1 -0
- package/dist/core/ir-style.js +136 -0
- package/dist/core/ir-style.js.map +1 -0
- package/dist/core/ir-types.d.ts +87 -0
- package/dist/core/ir-types.d.ts.map +1 -0
- package/dist/core/ir-types.js +2 -0
- package/dist/core/ir-types.js.map +1 -0
- package/dist/core/ir.d.ts +4 -0
- package/dist/core/ir.d.ts.map +1 -0
- package/dist/core/ir.js +3 -0
- package/dist/core/ir.js.map +1 -0
- package/dist/core/line-boxes.d.ts +22 -0
- package/dist/core/line-boxes.d.ts.map +1 -0
- package/dist/core/line-boxes.js +48 -0
- package/dist/core/line-boxes.js.map +1 -0
- package/dist/core/measure-range.d.ts +7 -0
- package/dist/core/measure-range.d.ts.map +1 -0
- package/dist/core/measure-range.js +15 -0
- package/dist/core/measure-range.js.map +1 -0
- package/dist/core/page-number-format.d.ts +28 -0
- package/dist/core/page-number-format.d.ts.map +1 -0
- package/dist/core/page-number-format.js +63 -0
- package/dist/core/page-number-format.js.map +1 -0
- package/dist/core/paginate-ir.d.ts +3 -0
- package/dist/core/paginate-ir.d.ts.map +1 -0
- package/dist/core/paginate-ir.js +116 -0
- package/dist/core/paginate-ir.js.map +1 -0
- package/dist/core/paginate.d.ts.map +1 -1
- package/dist/core/paginate.js +693 -92
- package/dist/core/paginate.js.map +1 -1
- package/dist/core/table-window.d.ts +8 -0
- package/dist/core/table-window.d.ts.map +1 -0
- package/dist/core/table-window.js +119 -0
- package/dist/core/table-window.js.map +1 -0
- package/dist/core/text-break.d.ts +6 -4
- package/dist/core/text-break.d.ts.map +1 -1
- package/dist/core/text-break.js +24 -61
- package/dist/core/text-break.js.map +1 -1
- package/dist/core/utils.d.ts.map +1 -1
- package/dist/core/utils.js +2 -1
- package/dist/core/utils.js.map +1 -1
- package/dist/export-pdf.d.ts +5 -0
- package/dist/export-pdf.d.ts.map +1 -0
- package/dist/export-pdf.js +7 -0
- package/dist/export-pdf.js.map +1 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/styles.css +16 -9
- package/dist/types.d.ts +26 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/writers/pdf-color.d.ts +7 -0
- package/dist/writers/pdf-color.d.ts.map +1 -0
- package/dist/writers/pdf-color.js +80 -0
- package/dist/writers/pdf-color.js.map +1 -0
- package/dist/writers/pdf.d.ts +9 -0
- package/dist/writers/pdf.d.ts.map +1 -0
- package/dist/writers/pdf.js +193 -0
- package/dist/writers/pdf.js.map +1 -0
- package/package.json +1 -1
package/dist/core/paginate.js
CHANGED
|
@@ -1,12 +1,95 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { canBreakElement } from "./avoid-break.js";
|
|
1
|
+
import { lineStartOffset } from "./text-break.js";
|
|
2
|
+
import { canBreakElement, isMonolithic } from "./avoid-break.js";
|
|
3
|
+
import { inlineLineBoxes, lineCount, groupLineBoxes } from "./line-boxes.js";
|
|
3
4
|
import { createComputedStyleCache } from "./computed-style.js";
|
|
4
5
|
import { waitForLayoutReady } from "./layout-ready.js";
|
|
6
|
+
import { measureRange } from "./measure-range.js";
|
|
7
|
+
import { formatPageNumber } from "./page-number-format.js";
|
|
8
|
+
import { createTableWindows } from "./table-window.js";
|
|
5
9
|
import { connectedClone, getBoxStyle } from "./utils.js";
|
|
6
10
|
import { resolvePageSize } from "../utils/page-size.js";
|
|
7
11
|
import { cloneChildrenInto, createPage, getDirectSlot, getEffectivePageSize, resolvePageSizeInPixels, } from "./utils.js";
|
|
8
12
|
const EMPTY_BY_PAGINATION_ATTRIBUTE = "data-paged-react-empty-by-pagination";
|
|
13
|
+
// Parent displays whose in-flow children are laid out top to bottom in source order.
|
|
14
|
+
const ORDERED_FLOW_DISPLAYS = new Set(["block", "flow-root", "list-item", "table-row-group"]);
|
|
15
|
+
const PAGE_NUMBER_SELECTOR = "[data-paged-react-page-number], [data-paged-react-total-pages], [data-paged-react-target-page]";
|
|
16
|
+
// Pagination passes when filled-in target page numbers keep changing the layout.
|
|
17
|
+
const MAX_PAGINATION_PASSES = 3;
|
|
9
18
|
export async function paginateDocument(ctx) {
|
|
19
|
+
let knownTargets = new Map();
|
|
20
|
+
let knownTotal = null;
|
|
21
|
+
for (let pass = 1;; pass++) {
|
|
22
|
+
const pages = await paginateSegments(ctx, knownTargets, knownTotal);
|
|
23
|
+
const targetPages = fillPageNumbers(pages);
|
|
24
|
+
// A filled-in target page or total page count can be wider than its placeholder and rewrap its
|
|
25
|
+
// line (a table of contents entry, or a header or footer band, which shrinks the body). If a
|
|
26
|
+
// page now overflows, paginate again with these numbers in place, until they stop changing.
|
|
27
|
+
const overflowing = pages.some((page) => {
|
|
28
|
+
const body = page.querySelector("[data-paged-react-page-body]");
|
|
29
|
+
return (body !== null &&
|
|
30
|
+
page.querySelector("[data-paged-react-target-page], [data-paged-react-total-pages]") !== null &&
|
|
31
|
+
body.scrollHeight > body.clientHeight);
|
|
32
|
+
});
|
|
33
|
+
const changed = knownTotal !== pages.length ||
|
|
34
|
+
targetPages.size !== knownTargets.size ||
|
|
35
|
+
Array.from(targetPages).some(([href, page]) => knownTargets.get(href) !== page);
|
|
36
|
+
if (!overflowing || !changed || pass === MAX_PAGINATION_PASSES || ctx.signal?.aborted) {
|
|
37
|
+
return pages;
|
|
38
|
+
}
|
|
39
|
+
knownTargets = targetPages;
|
|
40
|
+
knownTotal = pages.length;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Writes the page numbers into PageNumber, TotalPages and TargetPageNumber spans, once, after
|
|
45
|
+
* pagination. Returns each target's page, keyed by the span's href.
|
|
46
|
+
*/
|
|
47
|
+
function fillPageNumbers(pages) {
|
|
48
|
+
const pageOfId = new Map();
|
|
49
|
+
const format = (span, value) => formatPageNumber(value, span.getAttribute("data-paged-react-format"));
|
|
50
|
+
for (const page of pages) {
|
|
51
|
+
// The displayed number, which a segment's `pageNumberStart` can restart.
|
|
52
|
+
const number = Number(page.getAttribute("data-paged-react-number"));
|
|
53
|
+
// At scale 1 the page element is the segment clone itself, carrying the segment's id.
|
|
54
|
+
if (page.id && !pageOfId.has(page.id))
|
|
55
|
+
pageOfId.set(page.id, number);
|
|
56
|
+
for (const element of Array.from(page.querySelectorAll("[id]"))) {
|
|
57
|
+
if (!pageOfId.has(element.id))
|
|
58
|
+
pageOfId.set(element.id, number);
|
|
59
|
+
}
|
|
60
|
+
for (const span of Array.from(page.querySelectorAll("[data-paged-react-page-number]"))) {
|
|
61
|
+
span.textContent = format(span, number);
|
|
62
|
+
}
|
|
63
|
+
for (const span of Array.from(page.querySelectorAll("[data-paged-react-total-pages]"))) {
|
|
64
|
+
span.textContent = format(span, pages.length);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const targetPages = new Map();
|
|
68
|
+
for (const page of pages) {
|
|
69
|
+
for (const span of Array.from(page.querySelectorAll("[data-paged-react-target-page]"))) {
|
|
70
|
+
const href = span.getAttribute("data-paged-react-target-page");
|
|
71
|
+
if (href === null || !href.startsWith("#"))
|
|
72
|
+
continue;
|
|
73
|
+
// Like a browser: the fragment as written first, then percent-decoded. A malformed escape
|
|
74
|
+
// (id="100%") leaves the reference unresolved instead of failing the whole document.
|
|
75
|
+
let target = pageOfId.get(href.slice(1));
|
|
76
|
+
if (target === undefined) {
|
|
77
|
+
try {
|
|
78
|
+
target = pageOfId.get(decodeURIComponent(href.slice(1)));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (target === undefined)
|
|
85
|
+
continue;
|
|
86
|
+
span.textContent = format(span, target);
|
|
87
|
+
targetPages.set(href, span.textContent);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return targetPages;
|
|
91
|
+
}
|
|
92
|
+
async function paginateSegments(ctx, targetPages, totalPages) {
|
|
10
93
|
const { sourceRoot, pagesRoot, signal, options } = ctx;
|
|
11
94
|
const pages = [];
|
|
12
95
|
const scale = options?.scale ?? 1;
|
|
@@ -21,8 +104,27 @@ export async function paginateDocument(ctx) {
|
|
|
21
104
|
if (signal?.aborted)
|
|
22
105
|
return pages;
|
|
23
106
|
const sourceRootClone = connectedClone(sourceRoot);
|
|
107
|
+
// Page numbers are written after pagination; measure with a digit in place (or a target page
|
|
108
|
+
// already known from a previous pass) so headers, footers and contents lines keep their size.
|
|
109
|
+
for (const span of Array.from(sourceRootClone.querySelectorAll(PAGE_NUMBER_SELECTOR))) {
|
|
110
|
+
span.textContent = "0";
|
|
111
|
+
if (totalPages !== null && span.hasAttribute("data-paged-react-total-pages")) {
|
|
112
|
+
span.textContent = formatPageNumber(totalPages, span.getAttribute("data-paged-react-format"));
|
|
113
|
+
}
|
|
114
|
+
const href = span.getAttribute("data-paged-react-target-page");
|
|
115
|
+
if (href === null)
|
|
116
|
+
continue;
|
|
117
|
+
const known = targetPages.get(href);
|
|
118
|
+
if (known !== undefined)
|
|
119
|
+
span.textContent = known;
|
|
120
|
+
}
|
|
24
121
|
const segments = Array.from(sourceRootClone.querySelectorAll(":scope > [data-paged-react-segment-source]"));
|
|
122
|
+
let nextPageNumber = 1;
|
|
25
123
|
for (const [segmentIndex, segment] of segments.entries()) {
|
|
124
|
+
const pageNumberStart = segment.getAttribute("data-paged-react-page-number-start");
|
|
125
|
+
if (pageNumberStart !== null)
|
|
126
|
+
nextPageNumber = Number(pageNumberStart);
|
|
127
|
+
const firstPageNumber = nextPageNumber;
|
|
26
128
|
if (signal?.aborted)
|
|
27
129
|
return pages;
|
|
28
130
|
let segmentPageSize = getEffectivePageSize(segment);
|
|
@@ -84,58 +186,144 @@ export async function paginateDocument(ctx) {
|
|
|
84
186
|
const watermarks = Array.from(segment.children).filter((child) => {
|
|
85
187
|
return child.hasAttribute("data-paged-react-watermark-source");
|
|
86
188
|
});
|
|
87
|
-
const headerHeight = headerSlot?.offsetHeight ?? 0;
|
|
88
|
-
const footerHeight = footerSlot?.offsetHeight ?? 0;
|
|
89
189
|
const segBox = getBoxStyle(segment);
|
|
190
|
+
// bandPlacement="margin": header and footer go in the top and bottom margins, from the page
|
|
191
|
+
// edge, like Chrome's print headers and takumi. Their rows are at least the margins tall, so the
|
|
192
|
+
// body starts at the margin, and a taller band pushes it in (the margin grows).
|
|
193
|
+
const marginBands = segment.getAttribute("data-paged-react-band-placement") === "margin";
|
|
194
|
+
const placeBands = (created) => {
|
|
195
|
+
if (!marginBands)
|
|
196
|
+
return;
|
|
197
|
+
created.content.style.paddingTop = "0";
|
|
198
|
+
created.content.style.paddingBottom = "0";
|
|
199
|
+
created.content.style.gridTemplateRows = `minmax(${segBox.paddingTop}px, auto) minmax(0, 1fr) minmax(${segBox.paddingBottom}px, auto)`;
|
|
200
|
+
created.header.style.alignSelf = "start";
|
|
201
|
+
created.footer.style.alignSelf = "end";
|
|
202
|
+
// Explicit rows: a hidden or empty band must not let the body move up into its row.
|
|
203
|
+
created.header.style.gridRow = "1";
|
|
204
|
+
created.body.style.gridRow = "2";
|
|
205
|
+
created.footer.style.gridRow = "3";
|
|
206
|
+
for (const band of [created.header, created.footer]) {
|
|
207
|
+
if (band.ownerDocument.defaultView?.getComputedStyle(band).display === "contents") {
|
|
208
|
+
band.style.display = "block";
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
};
|
|
90
212
|
const segmentHeightOffset = segBox.paddingTop + segBox.paddingBottom + segBox.borderBottomWidth + segBox.borderTopWidth;
|
|
91
|
-
|
|
213
|
+
// Body height a header and footer leave, for the size check and for layout-less DOMs. In the
|
|
214
|
+
// margins a band only takes room beyond its margin.
|
|
215
|
+
const bodyHeightBetween = (header, footer) => {
|
|
216
|
+
const top = header?.offsetHeight ?? 0;
|
|
217
|
+
const bottom = footer?.offsetHeight ?? 0;
|
|
218
|
+
if (marginBands) {
|
|
219
|
+
return (contentPageSizePixels.height -
|
|
220
|
+
segBox.borderTopWidth -
|
|
221
|
+
segBox.borderBottomWidth -
|
|
222
|
+
Math.max(segBox.paddingTop, top) -
|
|
223
|
+
Math.max(segBox.paddingBottom, bottom));
|
|
224
|
+
}
|
|
225
|
+
return contentPageSizePixels.height - top - bottom - segmentHeightOffset;
|
|
226
|
+
};
|
|
227
|
+
const calculatedMaxBodyHeight = bodyHeightBetween(headerSlot, footerSlot);
|
|
92
228
|
if (calculatedMaxBodyHeight <= 0) {
|
|
93
229
|
console.warn(`Page size ${segmentPageSize.width} x ${segmentPageSize.height} is too small to fit header and footer content.`);
|
|
94
230
|
continue;
|
|
95
231
|
}
|
|
96
|
-
const repeatTableHeader = segment.getAttribute("data-paged-react-repeat-table-header")
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
232
|
+
const repeatTableHeader = segment.getAttribute("data-paged-react-repeat-table-header");
|
|
233
|
+
const repeatTableFooter = segment.getAttribute("data-paged-react-repeat-table-footer");
|
|
234
|
+
// Header and footer of a page: a `pages="first"` variant on the segment's first page, then an
|
|
235
|
+
// odd or even variant by page number, then the default slot.
|
|
236
|
+
const bandsFor = (bodyIndex) => {
|
|
237
|
+
const variant = (kind, pages) => segment.querySelector(`:scope > [data-paged-react-${kind}-source][data-paged-react-pages="${pages}"]`);
|
|
238
|
+
const parity = (firstPageNumber + bodyIndex) % 2 === 0 ? "even" : "odd";
|
|
239
|
+
const band = (kind, fallbackSlot) => {
|
|
240
|
+
const first = variant(kind, "first");
|
|
241
|
+
if (bodyIndex === 0 && first)
|
|
242
|
+
return first;
|
|
243
|
+
const byParity = variant(kind, parity);
|
|
244
|
+
if (byParity)
|
|
245
|
+
return byParity;
|
|
246
|
+
return fallbackSlot;
|
|
247
|
+
};
|
|
248
|
+
return { header: band("header", headerSlot), footer: band("footer", footerSlot) };
|
|
249
|
+
};
|
|
250
|
+
// The body height a page has depends on its header and footer: measure each combination once,
|
|
251
|
+
// in a hidden page that also checks candidate pages for overflow.
|
|
252
|
+
const measurements = new Map();
|
|
253
|
+
const pageBox = (bodyIndex) => {
|
|
254
|
+
const bands = bandsFor(bodyIndex);
|
|
255
|
+
const key = `${bands.header?.getAttribute("data-paged-react-pages")}|${bands.footer?.getAttribute("data-paged-react-pages")}`;
|
|
256
|
+
const known = measurements.get(key);
|
|
257
|
+
if (known) {
|
|
258
|
+
// The bands hold this page's own number while measuring: a longer one (e.g. LXXXVIII)
|
|
259
|
+
// can wrap its band and leave the body less room.
|
|
260
|
+
if (known.numbers.length && known.measurementBody) {
|
|
261
|
+
for (const span of known.numbers) {
|
|
262
|
+
span.textContent = formatPageNumber(firstPageNumber + bodyIndex, span.getAttribute("data-paged-react-format"));
|
|
263
|
+
}
|
|
264
|
+
known.maxBodyHeight = known.measurementBody.getBoundingClientRect().height;
|
|
265
|
+
}
|
|
266
|
+
return known;
|
|
267
|
+
}
|
|
268
|
+
const measurementPage = createPage({
|
|
269
|
+
segment,
|
|
270
|
+
pagesRoot,
|
|
271
|
+
pageSize: segmentPageSize,
|
|
272
|
+
contentPageSize,
|
|
273
|
+
scale,
|
|
274
|
+
bodySlot,
|
|
275
|
+
headerSlot: bands.header,
|
|
276
|
+
footerSlot: bands.footer,
|
|
277
|
+
pageNumber: segmentIndex + 1,
|
|
278
|
+
});
|
|
279
|
+
measurementPage.page.style.left = "-100000px";
|
|
280
|
+
measurementPage.page.style.position = "absolute";
|
|
281
|
+
measurementPage.page.style.top = "0";
|
|
282
|
+
measurementPage.page.style.visibility = "hidden";
|
|
283
|
+
if (scale !== 1) {
|
|
284
|
+
measurementPage.content.style.setProperty("scale", "1");
|
|
285
|
+
}
|
|
286
|
+
placeBands(measurementPage);
|
|
287
|
+
cloneChildrenInto(measurementPage.header, bands.header);
|
|
288
|
+
cloneChildrenInto(measurementPage.footer, bands.footer);
|
|
289
|
+
const numbers = Array.from(measurementPage.page.querySelectorAll("[data-paged-react-page-number]"));
|
|
290
|
+
for (const span of numbers) {
|
|
291
|
+
span.textContent = formatPageNumber(firstPageNumber + bodyIndex, span.getAttribute("data-paged-react-format"));
|
|
292
|
+
}
|
|
293
|
+
const measured = {
|
|
294
|
+
page: measurementPage.page,
|
|
295
|
+
maxBodyHeight: measurementPage.body.getBoundingClientRect().height,
|
|
296
|
+
measurementBody: measurementPage.body,
|
|
297
|
+
numbers,
|
|
298
|
+
};
|
|
299
|
+
if (measured.maxBodyHeight <= 0) {
|
|
300
|
+
measured.maxBodyHeight = bodyHeightBetween(bands.header, bands.footer);
|
|
301
|
+
measurementPage.page.remove();
|
|
302
|
+
measured.measurementBody = null;
|
|
303
|
+
}
|
|
304
|
+
measurements.set(key, measured);
|
|
305
|
+
return measured;
|
|
306
|
+
};
|
|
307
|
+
const removeMeasurementPages = () => {
|
|
308
|
+
for (const measured of measurements.values())
|
|
309
|
+
measured.page.remove();
|
|
310
|
+
};
|
|
124
311
|
console.time(`Segment ${segmentIndex + 1} pagination`);
|
|
125
312
|
const bodyPayload = {
|
|
126
313
|
body: bodySlot,
|
|
127
|
-
|
|
128
|
-
measurementBody,
|
|
314
|
+
pageBox,
|
|
129
315
|
repeatTableHeader,
|
|
316
|
+
repeatTableFooter,
|
|
130
317
|
signal,
|
|
131
318
|
};
|
|
132
319
|
let bodyIndex = 0;
|
|
133
320
|
for await (const bodySegment of bodySegmenter(bodyPayload)) {
|
|
134
321
|
if (signal?.aborted) {
|
|
135
|
-
|
|
322
|
+
removeMeasurementPages();
|
|
136
323
|
console.timeEnd(`Segment ${segmentIndex + 1} pagination`);
|
|
137
324
|
return pages;
|
|
138
325
|
}
|
|
326
|
+
const bands = bandsFor(bodyIndex);
|
|
139
327
|
const page = createPage({
|
|
140
328
|
segment,
|
|
141
329
|
pagesRoot,
|
|
@@ -143,14 +331,16 @@ export async function paginateDocument(ctx) {
|
|
|
143
331
|
contentPageSize,
|
|
144
332
|
scale,
|
|
145
333
|
bodySlot,
|
|
146
|
-
headerSlot,
|
|
147
|
-
footerSlot,
|
|
334
|
+
headerSlot: bands.header,
|
|
335
|
+
footerSlot: bands.footer,
|
|
148
336
|
pageNumber: segmentIndex + 1,
|
|
149
337
|
});
|
|
338
|
+
placeBands(page);
|
|
150
339
|
page.page.setAttribute("data-paged-react-segment-index", String(segmentIndex));
|
|
151
340
|
page.page.setAttribute("data-paged-react-body-segment-index", String(bodyIndex));
|
|
152
|
-
|
|
153
|
-
cloneChildrenInto(page.
|
|
341
|
+
page.page.setAttribute("data-paged-react-number", String(firstPageNumber + bodyIndex));
|
|
342
|
+
cloneChildrenInto(page.header, bands.header);
|
|
343
|
+
cloneChildrenInto(page.footer, bands.footer);
|
|
154
344
|
cloneChildrenInto(page.body, bodySegment);
|
|
155
345
|
for (const watermark of watermarks) {
|
|
156
346
|
page.page.appendChild(watermark.cloneNode(true));
|
|
@@ -158,7 +348,8 @@ export async function paginateDocument(ctx) {
|
|
|
158
348
|
pages.push(page.page);
|
|
159
349
|
bodyIndex += 1;
|
|
160
350
|
}
|
|
161
|
-
|
|
351
|
+
nextPageNumber = firstPageNumber + bodyIndex;
|
|
352
|
+
removeMeasurementPages();
|
|
162
353
|
console.timeEnd(`Segment ${segmentIndex + 1} pagination`);
|
|
163
354
|
}
|
|
164
355
|
sourceRootClone.remove();
|
|
@@ -166,7 +357,13 @@ export async function paginateDocument(ctx) {
|
|
|
166
357
|
return pages;
|
|
167
358
|
}
|
|
168
359
|
async function* bodySegmenter(ctx) {
|
|
169
|
-
const { body,
|
|
360
|
+
const { body, pageBox, repeatTableHeader, repeatTableFooter, signal } = ctx;
|
|
361
|
+
const repeatHead = repeatTableHeader !== "false";
|
|
362
|
+
const firstRowHead = repeatTableHeader === "true";
|
|
363
|
+
const repeatFoot = repeatTableFooter !== "false";
|
|
364
|
+
let pageIndex = 0;
|
|
365
|
+
let maxBodyHeight = pageBox(pageIndex).maxBodyHeight;
|
|
366
|
+
let measurementBody;
|
|
170
367
|
if (!body)
|
|
171
368
|
return;
|
|
172
369
|
const view = body.ownerDocument.defaultView;
|
|
@@ -174,16 +371,58 @@ async function* bodySegmenter(ctx) {
|
|
|
174
371
|
return;
|
|
175
372
|
const ownerWindow = view;
|
|
176
373
|
const styleCache = createComputedStyleCache();
|
|
374
|
+
const orderedFlowCache = new WeakMap();
|
|
177
375
|
const pageBreaks = Array.from(body.querySelectorAll("[data-paged-react-page-break]"));
|
|
376
|
+
// A table without a <tfoot> repeats its last body row: it becomes the <tfoot> before any row is
|
|
377
|
+
// parked by table windowing.
|
|
378
|
+
if (repeatTableFooter === "true") {
|
|
379
|
+
for (const table of Array.from(body.querySelectorAll("table"))) {
|
|
380
|
+
const lastBody = table.tBodies[table.tBodies.length - 1];
|
|
381
|
+
if (table.tFoot || !lastBody || lastBody.rows.length < 2)
|
|
382
|
+
continue;
|
|
383
|
+
const lastRow = lastBody.rows[lastBody.rows.length - 1];
|
|
384
|
+
if (lastRow)
|
|
385
|
+
table.createTFoot().append(lastRow);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
const tableWindows = createTableWindows(body, ownerWindow, maxBodyHeight);
|
|
178
389
|
let sliceMaxBodyHeight = maxBodyHeight;
|
|
390
|
+
let lastYield = performance.now();
|
|
391
|
+
let firstPage = true;
|
|
392
|
+
let forcedBreak = false;
|
|
393
|
+
// Set by keepWithNext when a better break exists inside an element it would move whole.
|
|
394
|
+
let rebreakAt = null;
|
|
395
|
+
let currentBodyTop = 0;
|
|
396
|
+
// Margins adjoining an unforced break are truncated (CSS Fragmentation 3, 5.2): the first
|
|
397
|
+
// blocks of a page lose their top margins, down to the first top padding or border.
|
|
398
|
+
const truncateLeadingMargins = () => {
|
|
399
|
+
for (let element = body.firstElementChild; element instanceof ownerWindow.HTMLElement; element = element.firstElementChild) {
|
|
400
|
+
const computed = ownerWindow.getComputedStyle(element);
|
|
401
|
+
if (computed.display.startsWith("inline") || computed.position === "absolute" || computed.position === "fixed")
|
|
402
|
+
break;
|
|
403
|
+
if (computed.marginTop !== "0px") {
|
|
404
|
+
element.style.marginTop = "0";
|
|
405
|
+
styleCache.invalidate(element);
|
|
406
|
+
}
|
|
407
|
+
if (parseFloat(computed.paddingTop) || parseFloat(computed.borderTopWidth))
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
};
|
|
179
411
|
while (true) {
|
|
180
412
|
if (signal?.aborted)
|
|
181
413
|
return;
|
|
414
|
+
// Each page has its own body height: a first-page or odd/even header or footer can differ.
|
|
415
|
+
({ maxBodyHeight, measurementBody } = pageBox(pageIndex));
|
|
182
416
|
sliceMaxBodyHeight = maxBodyHeight;
|
|
417
|
+
if (!firstPage && !forcedBreak)
|
|
418
|
+
truncateLeadingMargins();
|
|
419
|
+
firstPage = false;
|
|
420
|
+
forcedBreak = false;
|
|
183
421
|
const bodyRect = body.getBoundingClientRect();
|
|
422
|
+
currentBodyTop = bodyRect.top;
|
|
184
423
|
const bodyHeight = bodyRect.height;
|
|
185
424
|
const hasPageBreak = pageBreaks.some((pageBreak) => body.contains(pageBreak));
|
|
186
|
-
if (bodyHeight <= maxBodyHeight && !hasPageBreak) {
|
|
425
|
+
if (bodyHeight <= maxBodyHeight && !hasPageBreak && !tableWindows.pending()) {
|
|
187
426
|
if (measurementBody) {
|
|
188
427
|
cloneChildrenInto(measurementBody, body);
|
|
189
428
|
const bodyFits = measurementBody.scrollHeight <= measurementBody.clientHeight;
|
|
@@ -204,6 +443,16 @@ async function* bodySegmenter(ctx) {
|
|
|
204
443
|
while (true) {
|
|
205
444
|
const candidateMutations = [];
|
|
206
445
|
const candidate = bodySlice({ body, bodyRect, mutations: candidateMutations });
|
|
446
|
+
// A better break was found inside an element: slice the page again, ending exactly there.
|
|
447
|
+
const preferred = rebreakAt;
|
|
448
|
+
rebreakAt = null;
|
|
449
|
+
if (preferred !== null && preferred > 0 && preferred < sliceMaxBodyHeight) {
|
|
450
|
+
sliceMaxBodyHeight = preferred;
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
for (let element = candidate.segment.lastElementChild; element instanceof ownerWindow.HTMLElement; element = element.lastElementChild) {
|
|
454
|
+
element.style.marginBottom = "0";
|
|
455
|
+
}
|
|
207
456
|
if (!measurementBody) {
|
|
208
457
|
mutations = candidateMutations;
|
|
209
458
|
pageSlice = candidate.segment;
|
|
@@ -229,13 +478,26 @@ async function* bodySegmenter(ctx) {
|
|
|
229
478
|
}
|
|
230
479
|
}
|
|
231
480
|
yield pageSlice;
|
|
481
|
+
pageIndex += 1;
|
|
232
482
|
if (!mutations.length) {
|
|
483
|
+
// No progress is possible, so stop instead of repeating this page forever; whatever is
|
|
484
|
+
// still in the source is missing from the output, so say so.
|
|
485
|
+
if (body.textContent?.trim() || body.children.length) {
|
|
486
|
+
console.error("Paged React: pagination made no progress; the remaining content was dropped.", body);
|
|
487
|
+
}
|
|
233
488
|
return;
|
|
234
489
|
}
|
|
490
|
+
// Restore parked table rows before this page's rows leave the source, so the window never runs dry.
|
|
491
|
+
tableWindows.topUp();
|
|
235
492
|
for (const mutation of mutations) {
|
|
236
493
|
mutation();
|
|
237
494
|
}
|
|
238
|
-
|
|
495
|
+
// Yield to the browser in ~50 ms slices rather than after every page: each yield lets it run a
|
|
496
|
+
// full render of the growing page list, which cost ~25-30% of pagination time on 100+ pages.
|
|
497
|
+
if (performance.now() - lastYield > 50) {
|
|
498
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
499
|
+
lastYield = performance.now();
|
|
500
|
+
}
|
|
239
501
|
if (signal?.aborted)
|
|
240
502
|
return;
|
|
241
503
|
}
|
|
@@ -244,23 +506,95 @@ async function* bodySegmenter(ctx) {
|
|
|
244
506
|
const segment = parent.cloneNode(false);
|
|
245
507
|
let consumed = false;
|
|
246
508
|
let stopped = false;
|
|
509
|
+
// Elements placed whole on this page, newest last, so a heading can follow its next sibling.
|
|
510
|
+
const placed = [];
|
|
511
|
+
// `next` contributes nothing to this page. Elements before it that must not be separated from
|
|
512
|
+
// it (`break-after: avoid` / `break-before: avoid`) move to the next page too, as long as
|
|
513
|
+
// something else stays on this one.
|
|
514
|
+
const keepWithNext = (next) => {
|
|
515
|
+
let following = next;
|
|
516
|
+
for (let last = placed.at(-1); last; last = placed.at(-1)) {
|
|
517
|
+
if (last.mutationStart === 0 || !avoidsBreakBetween(last.element, following))
|
|
518
|
+
break;
|
|
519
|
+
// Rather than moving all of it, break inside it at its latest allowed boundary (the
|
|
520
|
+
// highest-ranked break left on this page), e.g. before a heading that closes a wrapper.
|
|
521
|
+
const inner = interiorBreak(last.element, bodyRect);
|
|
522
|
+
if (inner !== null) {
|
|
523
|
+
rebreakAt = inner;
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
placed.pop();
|
|
527
|
+
while (segment.lastChild && segment.lastChild !== last.clone)
|
|
528
|
+
segment.lastChild.remove();
|
|
529
|
+
last.clone.parentNode?.removeChild(last.clone);
|
|
530
|
+
mutations.length = last.mutationStart;
|
|
531
|
+
consumed = last.consumedBefore;
|
|
532
|
+
following = last.element;
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
// Without repeated headers only a table's first fragment shows its <thead>: once rows of the
|
|
536
|
+
// table are placed, the header leaves the source with them.
|
|
537
|
+
const consumeTableHeaderWith = (target) => {
|
|
538
|
+
const head = parent instanceof ownerWindow.HTMLTableElement ? parent.tHead : null;
|
|
539
|
+
if (!repeatHead && head && target !== head && target.tagName !== "COLGROUP" && target.tagName !== "CAPTION") {
|
|
540
|
+
mutations.push(() => head.remove());
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
// Everything on this page so far must stay with `next` (a heading starting the page): moving
|
|
544
|
+
// `next` to the next page would take all of it along, so the page could not make progress.
|
|
545
|
+
const onlyKeptWithNext = (next) => {
|
|
546
|
+
let following = next;
|
|
547
|
+
for (let index = placed.length - 1; index >= 0; index--) {
|
|
548
|
+
const entry = placed.at(index);
|
|
549
|
+
if (!entry || !avoidsBreakBetween(entry.element, following))
|
|
550
|
+
return false;
|
|
551
|
+
if (entry.mutationStart === 0)
|
|
552
|
+
return true;
|
|
553
|
+
following = entry.element;
|
|
554
|
+
}
|
|
555
|
+
return false;
|
|
556
|
+
};
|
|
247
557
|
const parentStyle = styleCache.get(parent);
|
|
248
|
-
|
|
558
|
+
// Ancestors being walked continue on the next page and are sliced (see sliceFragment), so
|
|
559
|
+
// their bottom padding, border and margin take no room on this page.
|
|
560
|
+
const parentOffset = 0;
|
|
561
|
+
const orderedFlow = isOrderedFlow(parent);
|
|
249
562
|
for (const target of Array.from(parent.childNodes)) {
|
|
250
563
|
if (target instanceof ownerWindow.Element) {
|
|
251
564
|
if (target.hasAttribute("data-paged-react-page-break")) {
|
|
252
|
-
|
|
565
|
+
// A break below the page window belongs to a later page: end this page without
|
|
566
|
+
// consuming it, otherwise it is removed here and never breaks where it stands.
|
|
567
|
+
const breakTop = target.getBoundingClientRect().top + parentOffset + superParentOffset - bodyRect.top;
|
|
568
|
+
if (breakTop <= sliceMaxBodyHeight) {
|
|
569
|
+
mutations.push(() => {
|
|
570
|
+
target.remove();
|
|
571
|
+
forcedBreak = true;
|
|
572
|
+
});
|
|
573
|
+
}
|
|
253
574
|
return { consumed, segment, stopped: true };
|
|
254
575
|
}
|
|
576
|
+
// Column definitions apply to every slice of a table: copy them onto each page and keep
|
|
577
|
+
// them in the source. Losing them changes column widths, so slices measured against the
|
|
578
|
+
// source layout overflow the page.
|
|
579
|
+
if (parent instanceof ownerWindow.HTMLTableElement && target.tagName === "COLGROUP") {
|
|
580
|
+
segment.appendChild(target.cloneNode(true));
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
// A table being split repeats its <tfoot> at the bottom of each fragment; the caller adds
|
|
584
|
+
// it. Its last fragment fits whole and keeps the original.
|
|
585
|
+
if (repeatFoot && parent instanceof ownerWindow.HTMLTableElement && target === parent.tFoot) {
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
255
588
|
const targetRect = target.getBoundingClientRect();
|
|
256
589
|
const targetStyle = styleCache.get(target);
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
590
|
+
// Border box only: a bottom margin at the end of the page is truncated.
|
|
591
|
+
const targetBottom = targetRect.bottom + superParentOffset + parentOffset - bodyRect.top;
|
|
592
|
+
// In ordered flow this child and every later one start below the page window, so none of
|
|
593
|
+
// them can land on this page.
|
|
594
|
+
if (orderedFlow && mutations.length > 0 && targetRect.top - bodyRect.top > sliceMaxBodyHeight) {
|
|
595
|
+
keepWithNext(target);
|
|
596
|
+
return { consumed, segment, stopped: true, pastWindow: true };
|
|
597
|
+
}
|
|
264
598
|
const isEmptyShell = target.children.length === 0 &&
|
|
265
599
|
target.textContent !== null &&
|
|
266
600
|
target.textContent.trim() === "";
|
|
@@ -270,70 +604,137 @@ async function* bodySegmenter(ctx) {
|
|
|
270
604
|
targetStyle.paddingBottom -
|
|
271
605
|
targetStyle.borderTopWidth -
|
|
272
606
|
targetStyle.borderBottomWidth;
|
|
273
|
-
|
|
607
|
+
// Table cells keep the row's column structure: an empty cell is always copied into the
|
|
608
|
+
// fragment and never dropped.
|
|
609
|
+
const tableCell = target instanceof ownerWindow.HTMLTableCellElement;
|
|
610
|
+
// A box whose content pagination already placed holds nothing more to show. If it
|
|
611
|
+
// crosses the page end (fixed height), drop it: it can never fit and would stall pages.
|
|
612
|
+
if (target.hasAttribute(EMPTY_BY_PAGINATION_ATTRIBUTE) &&
|
|
613
|
+
(targetContentHeight <= 0 || (!tableCell && targetBottom > sliceMaxBodyHeight))) {
|
|
274
614
|
mutations.push(() => target.remove());
|
|
275
615
|
continue;
|
|
276
616
|
}
|
|
277
|
-
|
|
617
|
+
// Empty elements (<br>, <hr>, <img>, spacers) go on the page only when they fit there;
|
|
618
|
+
// otherwise they wait in the source for the page they belong to.
|
|
619
|
+
if (tableCell || targetBottom <= sliceMaxBodyHeight)
|
|
620
|
+
segment.appendChild(target.cloneNode(true));
|
|
278
621
|
if (targetBottom <= sliceMaxBodyHeight) {
|
|
279
622
|
mutations.push(() => target.remove());
|
|
280
623
|
consumed = true;
|
|
281
624
|
}
|
|
282
625
|
continue;
|
|
283
626
|
}
|
|
284
|
-
const
|
|
627
|
+
const targetRequiredPageHeight = targetRect.height + Math.max(0, targetStyle.marginTop) + Math.max(0, targetStyle.marginBottom);
|
|
628
|
+
// `break-inside: avoid` is a preference. Like Chrome, a block that is too tall for any page
|
|
629
|
+
// first moves to a fresh page (see below) and is split there instead of being clipped.
|
|
630
|
+
const canBreakTarget = canBreakElement(target) ||
|
|
631
|
+
((mutations.length === 0 || onlyKeptWithNext(target)) &&
|
|
632
|
+
targetRequiredPageHeight > maxBodyHeight &&
|
|
633
|
+
!isMonolithic(target));
|
|
285
634
|
const hasNestedPageBreak = pageBreaks.some((pageBreak) => target.contains(pageBreak));
|
|
286
635
|
if (targetBottom <= sliceMaxBodyHeight &&
|
|
287
636
|
!hasNestedPageBreak &&
|
|
288
637
|
targetStyle.display !== "contents") {
|
|
289
638
|
// Keep pagination-created empty shells that still have box height.
|
|
290
|
-
|
|
639
|
+
const clone = target.cloneNode(true);
|
|
640
|
+
segment.appendChild(clone);
|
|
291
641
|
// Keep table headers on the current page.
|
|
292
642
|
if (parent instanceof ownerWindow.HTMLTableElement && target.tagName === "THEAD")
|
|
293
643
|
continue;
|
|
294
|
-
// Keep the first body row
|
|
295
|
-
if (
|
|
644
|
+
// Keep the first body row as the header of a table without a <thead>.
|
|
645
|
+
if (firstRowHead &&
|
|
296
646
|
parent instanceof ownerWindow.HTMLTableSectionElement &&
|
|
297
647
|
parent.parentElement instanceof ownerWindow.HTMLTableElement &&
|
|
298
648
|
!parent.parentElement.tHead &&
|
|
299
649
|
target === parent.rows[0]) {
|
|
300
650
|
continue;
|
|
301
651
|
}
|
|
652
|
+
placed.push({ element: target, clone, mutationStart: mutations.length, consumedBefore: consumed });
|
|
302
653
|
mutations.push(() => {
|
|
303
654
|
// Remove the source node after cloning it into the page.
|
|
304
|
-
cleanupPaginationTarget(target, parent,
|
|
655
|
+
cleanupPaginationTarget(target, parent, firstRowHead);
|
|
305
656
|
});
|
|
657
|
+
consumeTableHeaderWith(target);
|
|
306
658
|
consumed = true;
|
|
307
659
|
}
|
|
308
660
|
else if (canBreakTarget) {
|
|
309
|
-
const
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
661
|
+
const lineLimit = lineFragmentLimit(target, targetRect, bodyRect, parentOffset + superParentOffset);
|
|
662
|
+
// Too few lines would stay on this page (orphans), so the block starts on the next one.
|
|
663
|
+
if (lineLimit === "next-page" && mutations.length > 0) {
|
|
664
|
+
keepWithNext(target);
|
|
665
|
+
return { consumed, segment, stopped: true };
|
|
666
|
+
}
|
|
667
|
+
// Stop the split early enough to leave `widows` lines for the next page.
|
|
668
|
+
const pageLimit = sliceMaxBodyHeight;
|
|
669
|
+
if (typeof lineLimit === "number") {
|
|
670
|
+
sliceMaxBodyHeight = Math.min(sliceMaxBodyHeight, lineLimit);
|
|
671
|
+
}
|
|
672
|
+
// Like Chrome's print, a table continuing on the next page repeats its <tfoot> at the
|
|
673
|
+
// bottom of this fragment, so leave room for it below the rows.
|
|
674
|
+
const repeatedFooter = repeatFoot && target instanceof ownerWindow.HTMLTableElement ? target.tFoot : null;
|
|
675
|
+
if (repeatedFooter)
|
|
676
|
+
sliceMaxBodyHeight -= repeatedFooter.getBoundingClientRect().height;
|
|
677
|
+
let childSegment;
|
|
678
|
+
try {
|
|
679
|
+
childSegment = bodySlice({
|
|
680
|
+
body,
|
|
681
|
+
bodyRect,
|
|
682
|
+
mutations,
|
|
683
|
+
parent: target,
|
|
684
|
+
superParentOffset: parentOffset + superParentOffset,
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
finally {
|
|
688
|
+
sliceMaxBodyHeight = pageLimit;
|
|
689
|
+
}
|
|
690
|
+
if (repeatedFooter && childSegment.consumed) {
|
|
691
|
+
childSegment.segment.appendChild(repeatedFooter.cloneNode(true));
|
|
692
|
+
}
|
|
316
693
|
if (childSegment.segment.childNodes.length && childSegment.consumed) {
|
|
317
694
|
segment.appendChild(childSegment.segment);
|
|
318
695
|
consumed = true;
|
|
696
|
+
placed.length = 0;
|
|
697
|
+
consumeTableHeaderWith(target);
|
|
698
|
+
sliceFragment(childSegment.segment, target, mutations);
|
|
319
699
|
}
|
|
320
700
|
if (childSegment.stopped) {
|
|
701
|
+
// The child only ran out of content inside the page window. Later siblings start below
|
|
702
|
+
// it in ordered flow; in grids, flex rows and tables they may sit beside it, so go on.
|
|
703
|
+
if (childSegment.pastWindow) {
|
|
704
|
+
if (!orderedFlow)
|
|
705
|
+
continue;
|
|
706
|
+
if (!childSegment.consumed)
|
|
707
|
+
keepWithNext(target);
|
|
708
|
+
return { consumed, segment, stopped: true, pastWindow: true };
|
|
709
|
+
}
|
|
321
710
|
if ((parentStyle.display === "flex" || parentStyle.display === "inline-flex") &&
|
|
322
711
|
parentStyle.flexDirection !== "column" &&
|
|
323
712
|
parentStyle.flexDirection !== "column-reverse") {
|
|
324
713
|
stopped = true;
|
|
325
714
|
continue;
|
|
326
715
|
}
|
|
716
|
+
if (!childSegment.consumed)
|
|
717
|
+
keepWithNext(target);
|
|
718
|
+
return { consumed, segment, stopped: true };
|
|
719
|
+
}
|
|
720
|
+
// The block crosses the page end but not even its first line fits: it moves to the next
|
|
721
|
+
// page as a whole, and what must stay with it (a heading before it) moves too.
|
|
722
|
+
if (orderedFlow &&
|
|
723
|
+
!childSegment.consumed &&
|
|
724
|
+
mutations.length > 0 &&
|
|
725
|
+
targetBottom > sliceMaxBodyHeight) {
|
|
726
|
+
keepWithNext(target);
|
|
327
727
|
return { consumed, segment, stopped: true };
|
|
328
728
|
}
|
|
329
729
|
}
|
|
330
730
|
else {
|
|
331
|
-
if (consumed)
|
|
731
|
+
if (consumed) {
|
|
732
|
+
keepWithNext(target);
|
|
332
733
|
return { consumed, segment, stopped: true };
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
734
|
+
}
|
|
735
|
+
if (mutations.length > 0 &&
|
|
736
|
+
(targetRequiredPageHeight <= maxBodyHeight || !isMonolithic(target))) {
|
|
737
|
+
keepWithNext(target);
|
|
337
738
|
return { consumed, segment, stopped: true };
|
|
338
739
|
}
|
|
339
740
|
console.error("Paged React: unbreakable element exceeds one page and will be clipped.", target);
|
|
@@ -343,7 +744,7 @@ async function* bodySegmenter(ctx) {
|
|
|
343
744
|
}
|
|
344
745
|
}
|
|
345
746
|
if (target instanceof ownerWindow.Text) {
|
|
346
|
-
const textRange = body.ownerDocument
|
|
747
|
+
const textRange = measureRange(body.ownerDocument);
|
|
347
748
|
textRange.selectNode(target);
|
|
348
749
|
const textRects = Array.from(textRange.getClientRects());
|
|
349
750
|
// Remove text nodes that no longer render any line boxes.
|
|
@@ -363,36 +764,236 @@ async function* bodySegmenter(ctx) {
|
|
|
363
764
|
}
|
|
364
765
|
// Keep text that fully fits on the current page.
|
|
365
766
|
if (textBottom <= sliceMaxBodyHeight) {
|
|
767
|
+
if (target.data.trim())
|
|
768
|
+
placed.length = 0;
|
|
366
769
|
segment.append(target.data);
|
|
367
|
-
mutations.push(() =>
|
|
770
|
+
mutations.push(() => {
|
|
771
|
+
const textParent = target.parentElement;
|
|
772
|
+
target.remove();
|
|
773
|
+
if (textParent && !textParent.children.length && !textParent.textContent?.trim()) {
|
|
774
|
+
textParent.setAttribute(EMPTY_BY_PAGINATION_ATTRIBUTE, "");
|
|
775
|
+
}
|
|
776
|
+
});
|
|
368
777
|
consumed = true;
|
|
369
778
|
continue;
|
|
370
779
|
}
|
|
371
780
|
// Leave text alone if it starts below the current page window.
|
|
372
781
|
if (textTop > sliceMaxBodyHeight)
|
|
373
782
|
continue;
|
|
374
|
-
// Split text
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
mutations.push(() => target.replaceWith(remaining));
|
|
783
|
+
// Split text at the first line that does not fit: earlier lines stay on this page, the
|
|
784
|
+
// rest stays in the source as one text node. Only that boundary is measured.
|
|
785
|
+
// One entry per line box: pre-formatted text reports an extra rect per newline.
|
|
786
|
+
const lines = groupLineBoxes(textRects);
|
|
787
|
+
const offset = parentOffset + superParentOffset - bodyRect.top;
|
|
788
|
+
const firstOverflow = lines.findIndex((line) => line.bottom + offset > sliceMaxBodyHeight);
|
|
789
|
+
const overflowLine = lines[firstOverflow];
|
|
790
|
+
const cut = overflowLine ? lineStartOffset(target, overflowLine) : target.data.length;
|
|
791
|
+
// Splitting at 0 would place nothing and leave the page unchanged.
|
|
792
|
+
if (cut > 0 && cut < target.data.length) {
|
|
793
|
+
if (target.data.slice(0, cut).trim())
|
|
794
|
+
placed.length = 0;
|
|
795
|
+
segment.append(target.data.slice(0, cut));
|
|
796
|
+
consumed = true;
|
|
797
|
+
mutations.push(() => target.deleteData(0, cut));
|
|
390
798
|
}
|
|
391
799
|
}
|
|
392
800
|
}
|
|
393
801
|
return { consumed, segment, stopped };
|
|
394
802
|
}
|
|
395
|
-
|
|
803
|
+
/**
|
|
804
|
+
* A block split at the page end is sliced like Chrome's default `box-decoration-break: slice`:
|
|
805
|
+
* the fragment on this page has no bottom padding, border or margin, and the part left in the
|
|
806
|
+
* source (the next page) no top ones.
|
|
807
|
+
*/
|
|
808
|
+
function sliceFragment(fragment, source, mutations) {
|
|
809
|
+
fragment.style.paddingBottom = "0";
|
|
810
|
+
fragment.style.borderBottomWidth = "0";
|
|
811
|
+
fragment.style.marginBottom = "0";
|
|
812
|
+
// A box taller than its content (a fixed height or min-height, e.g. table cells with a set
|
|
813
|
+
// height) is split like Chrome splits it: this fragment shrinks to the content placed here, the
|
|
814
|
+
// continuation keeps only the height left below the page end.
|
|
815
|
+
const leftover = fixedHeightLeftover(source);
|
|
816
|
+
if (leftover !== null) {
|
|
817
|
+
fragment.style.height = "auto";
|
|
818
|
+
fragment.style.minHeight = "0";
|
|
819
|
+
}
|
|
820
|
+
mutations.push(() => {
|
|
821
|
+
if (leftover !== null) {
|
|
822
|
+
source.style.height = `${leftover}px`;
|
|
823
|
+
source.style.minHeight = "0";
|
|
824
|
+
}
|
|
825
|
+
source.style.paddingTop = "0";
|
|
826
|
+
source.style.borderTopWidth = "0";
|
|
827
|
+
source.style.marginTop = "0";
|
|
828
|
+
styleCache.invalidate(source);
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* Cells of `row` that span rows below it would disappear with it and shift every later row's
|
|
833
|
+
* cells into the wrong columns. Before the first row of a section leaves the source, each such
|
|
834
|
+
* cell continues as an empty cell in the next row, at the same column, spanning one row less.
|
|
835
|
+
*/
|
|
836
|
+
function carryRowSpans(row) {
|
|
837
|
+
const section = row.parentElement;
|
|
838
|
+
const next = row.nextElementSibling;
|
|
839
|
+
if (!(section instanceof ownerWindow.HTMLTableSectionElement) || section.rows[0] !== row)
|
|
840
|
+
return;
|
|
841
|
+
if (!(next instanceof ownerWindow.HTMLTableRowElement))
|
|
842
|
+
return;
|
|
843
|
+
// In a section's first row, a cell's column is the sum of the colspans before it.
|
|
844
|
+
const carried = [];
|
|
845
|
+
let column = 0;
|
|
846
|
+
for (const cell of Array.from(row.cells)) {
|
|
847
|
+
if (cell.rowSpan > 1) {
|
|
848
|
+
const continuation = cell.cloneNode(false);
|
|
849
|
+
continuation.rowSpan = cell.rowSpan - 1;
|
|
850
|
+
carried.push({ column, cell: continuation });
|
|
851
|
+
}
|
|
852
|
+
column += cell.colSpan;
|
|
853
|
+
}
|
|
854
|
+
if (!carried.length)
|
|
855
|
+
return;
|
|
856
|
+
// The next row's own cells fill the columns the carried cells leave free.
|
|
857
|
+
const taken = new Set(carried.flatMap(({ column: start, cell }) => Array.from({ length: cell.colSpan }, (_, i) => start + i)));
|
|
858
|
+
const placedAt = [];
|
|
859
|
+
let free = 0;
|
|
860
|
+
for (const cell of Array.from(next.cells)) {
|
|
861
|
+
while (taken.has(free))
|
|
862
|
+
free++;
|
|
863
|
+
placedAt.push({ column: free, cell });
|
|
864
|
+
free += cell.colSpan;
|
|
865
|
+
}
|
|
866
|
+
for (const { column: start, cell } of carried) {
|
|
867
|
+
const before = placedAt.find((entry) => entry.column > start)?.cell ?? null;
|
|
868
|
+
next.insertBefore(cell, before);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* The latest place inside `element` where the page may break without violating an `avoid`:
|
|
873
|
+
* the bottom of a child followed by a sibling it need not stay with, searched from the deepest
|
|
874
|
+
* level of the last-child chain up (deeper boundaries come later on the page). Null when the
|
|
875
|
+
* element must not be broken or has no such boundary.
|
|
876
|
+
*/
|
|
877
|
+
function interiorBreak(element, bodyRect) {
|
|
878
|
+
const levels = [];
|
|
879
|
+
for (let level = element; level && canBreakElement(level) && isOrderedFlow(level); level = level.lastElementChild) {
|
|
880
|
+
levels.push(level);
|
|
881
|
+
}
|
|
882
|
+
for (const level of levels.reverse()) {
|
|
883
|
+
const children = Array.from(level.children);
|
|
884
|
+
for (let index = children.length - 1; index > 0; index--) {
|
|
885
|
+
const before = children[index - 1];
|
|
886
|
+
if (!avoidsBreakBetween(before, children[index])) {
|
|
887
|
+
const bottom = before.getBoundingClientRect().bottom - bodyRect.top;
|
|
888
|
+
return bottom > 0 ? bottom : null;
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
return null;
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Height of `element` below the current page end when CSS gives it a fixed height (`height` or
|
|
896
|
+
* `min-height` as a length), null when it is sized by its content. Uses the Typed OM, which keeps
|
|
897
|
+
* `auto` where getComputedStyle reports used pixels; layout-less DOMs (jsdom) lack it.
|
|
898
|
+
*/
|
|
899
|
+
function fixedHeightLeftover(element) {
|
|
900
|
+
if (typeof element.computedStyleMap !== "function")
|
|
901
|
+
return null;
|
|
902
|
+
const styles = element.computedStyleMap();
|
|
903
|
+
const fixed = (value) => String(value).endsWith("px") && String(value) !== "0px";
|
|
904
|
+
if (!fixed(styles.get("height")) && !fixed(styles.get("min-height")))
|
|
905
|
+
return null;
|
|
906
|
+
const pageEnd = currentBodyTop + sliceMaxBodyHeight;
|
|
907
|
+
return Math.max(0, element.getBoundingClientRect().bottom - pageEnd);
|
|
908
|
+
}
|
|
909
|
+
/** CSS `break-after` / `break-before: avoid` between two adjacent siblings. */
|
|
910
|
+
function avoidsBreakBetween(previous, next) {
|
|
911
|
+
const avoid = (value) => value === "avoid" || value === "avoid-page";
|
|
912
|
+
const blockLevel = (element) => !ownerWindow.getComputedStyle(element).display.startsWith("inline");
|
|
913
|
+
// `break-after` propagates up from a last child, `break-before` from a first child.
|
|
914
|
+
for (let element = previous; element && blockLevel(element); element = element.lastElementChild) {
|
|
915
|
+
if (avoid(ownerWindow.getComputedStyle(element).breakAfter))
|
|
916
|
+
return true;
|
|
917
|
+
}
|
|
918
|
+
for (let element = next; element && blockLevel(element); element = element.firstElementChild) {
|
|
919
|
+
if (avoid(ownerWindow.getComputedStyle(element).breakBefore))
|
|
920
|
+
return true;
|
|
921
|
+
}
|
|
922
|
+
return false;
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Whether every child of `parent` starts at or below the previous one, so a sibling walk may end
|
|
926
|
+
* at the first child that starts below the page window. Computed once per parent: pagination
|
|
927
|
+
* only removes children and splits text, which cannot break the ordering.
|
|
928
|
+
*/
|
|
929
|
+
function isOrderedFlow(parent) {
|
|
930
|
+
const cached = orderedFlowCache.get(parent);
|
|
931
|
+
if (cached !== undefined)
|
|
932
|
+
return cached;
|
|
933
|
+
// "" is what DOMs without layout (jsdom) report for properties they do not implement.
|
|
934
|
+
const isInitial = (value, ...initial) => value === "" || initial.includes(value);
|
|
935
|
+
const parentComputed = ownerWindow.getComputedStyle(parent);
|
|
936
|
+
// Tables lay out caption/thead/tfoot in their own order, whatever the DOM order is.
|
|
937
|
+
let ordered = !(parent instanceof ownerWindow.HTMLTableElement) &&
|
|
938
|
+
ORDERED_FLOW_DISPLAYS.has(styleCache.get(parent).display) &&
|
|
939
|
+
isInitial(parentComputed.columnCount, "auto", "1") &&
|
|
940
|
+
isInitial(parentComputed.columnWidth, "auto");
|
|
941
|
+
for (const child of Array.from(parent.children)) {
|
|
942
|
+
if (!ordered)
|
|
943
|
+
break;
|
|
944
|
+
const computed = ownerWindow.getComputedStyle(child);
|
|
945
|
+
const box = styleCache.get(child);
|
|
946
|
+
// Inline content, out-of-flow boxes, floats, shifted boxes and negative margins can all put a
|
|
947
|
+
// later child above an earlier one.
|
|
948
|
+
ordered =
|
|
949
|
+
!computed.display.startsWith("inline") &&
|
|
950
|
+
(isInitial(computed.position, "static") ||
|
|
951
|
+
(computed.position === "relative" &&
|
|
952
|
+
isInitial(computed.top, "auto", "0px") &&
|
|
953
|
+
isInitial(computed.bottom, "auto", "0px"))) &&
|
|
954
|
+
isInitial(computed.float, "none") &&
|
|
955
|
+
isInitial(computed.transform, "none") &&
|
|
956
|
+
box.marginTop >= 0 &&
|
|
957
|
+
box.marginBottom >= 0;
|
|
958
|
+
}
|
|
959
|
+
orderedFlowCache.set(parent, ordered);
|
|
960
|
+
return ordered;
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Applies CSS `orphans` / `widows` to a block of inline content that crosses the page end.
|
|
964
|
+
* Returns a lower slice height that keeps enough lines for the next page, "next-page" when
|
|
965
|
+
* fewer than `orphans` lines could stay on this page, or null when no adjustment is needed.
|
|
966
|
+
*/
|
|
967
|
+
function lineFragmentLimit(target, targetRect, bodyRect, offset) {
|
|
968
|
+
// Starts below this page: none of its lines can land here, so skip measuring them.
|
|
969
|
+
if (targetRect.top - bodyRect.top >= sliceMaxBodyHeight)
|
|
970
|
+
return null;
|
|
971
|
+
const lines = inlineLineBoxes(target, ownerWindow);
|
|
972
|
+
if (!lines || lines.length < 2)
|
|
973
|
+
return null;
|
|
974
|
+
// The block is split, so its bottom padding, border and margin are not on this page.
|
|
975
|
+
const bottomOffset = offset;
|
|
976
|
+
const lineBottoms = lines.map((line) => line.bottom + bottomOffset - bodyRect.top);
|
|
977
|
+
const fitting = lineBottoms.filter((bottom) => bottom <= sliceMaxBodyHeight).length;
|
|
978
|
+
if (fitting === 0 || fitting === lines.length)
|
|
979
|
+
return null;
|
|
980
|
+
const computed = ownerWindow.getComputedStyle(target);
|
|
981
|
+
const orphans = lineCount(computed.orphans);
|
|
982
|
+
const widows = lineCount(computed.widows);
|
|
983
|
+
let keep = Math.min(fitting, lines.length - widows);
|
|
984
|
+
// Too few lines for both (fewer than orphans + widows): like Chrome, orphans win and the
|
|
985
|
+
// block breaks right after them, leaving fewer widows than asked for.
|
|
986
|
+
if (keep < orphans && fitting >= orphans)
|
|
987
|
+
keep = orphans;
|
|
988
|
+
if (keep < orphans)
|
|
989
|
+
return "next-page";
|
|
990
|
+
if (keep < fitting)
|
|
991
|
+
return (lineBottoms[keep - 1] ?? 0) + 0.5;
|
|
992
|
+
return null;
|
|
993
|
+
}
|
|
994
|
+
function cleanupPaginationTarget(target, parent, firstRowHead) {
|
|
995
|
+
if (target instanceof ownerWindow.HTMLTableRowElement)
|
|
996
|
+
carryRowSpans(target);
|
|
396
997
|
if (target.tagName === "LI" && parent instanceof ownerWindow.HTMLOListElement) {
|
|
397
998
|
if (parent.reversed)
|
|
398
999
|
parent.start -= 1;
|
|
@@ -409,7 +1010,7 @@ async function* bodySegmenter(ctx) {
|
|
|
409
1010
|
const table = parent.parentElement;
|
|
410
1011
|
if (parent.rows.length === 0)
|
|
411
1012
|
parent.remove();
|
|
412
|
-
if (
|
|
1013
|
+
if (firstRowHead &&
|
|
413
1014
|
table instanceof ownerWindow.HTMLTableElement &&
|
|
414
1015
|
!table.tHead &&
|
|
415
1016
|
parent.rows.length === 1) {
|