paged-react 0.2.5 → 0.3.0

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