@xiee/utils 1.14.126 → 1.14.128

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/js/pages.js CHANGED
@@ -1,29 +1,93 @@
1
- // move elements into page boxes such that each box contains as many elements as
2
- // possible and will not exceed the given size (e.g. A4 paper)
1
+ // Paginate an HTML page: move elements into page boxes (e.g., A4 paper) such that
2
+ // each box holds as much content as possible without exceeding the page height.
3
+ //
4
+ // How it works:
5
+ // 1. The content root (e.g., <main>) is emptied, and its children are put on
6
+ // pages one by one (fill() -> place()). Only the current page is in the DOM, so
7
+ // measuring it is cheap (box.scrollHeight > H means the page overflows).
8
+ // 2. When an element makes the page overflow, split() puts as much of it as
9
+ // possible on the current page and returns the rest, which goes to the next
10
+ // page. An element can be broken in different ways (kindOf()): block elements
11
+ // (e.g., lists and quotes) are cloned and their children are moved into the
12
+ // clone one by one, with the child that overflows broken recursively; text,
13
+ // table rows, and code lines are broken by lines/rows. Every piece of a broken
14
+ // element has the classes pagesjs-fragmented, fragment-first, fragment-last
15
+ // (the pieces can be styled differently in pages.css).
16
+ // 3. Each page contains empty copies of the ancestors of the content root, so
17
+ // CSS selectors that depend on them still work (see ctx()).
18
+ // 4. In the end, page numbers and titles are added to the headers/footers.
3
19
  (d => {
20
+
21
+ // --- Utilities -----------------------------------------------------
22
+
4
23
  function $(s, el = d) { return el?.querySelector(s); }
5
24
  function $$(s, el = d) { return el ? el.querySelectorAll(s) : []; }
6
25
  function nChild(el) { return el.childElementCount; }
7
26
 
8
- const tpl = d.createElement('div'), book = $$('h1').length > 1, boxes = [],
9
- fr_tag = ['TABLE', 'UL', 'OL', 'BLOCKQUOTE'],
10
- box_tag = ['DIV', 'NAV', 'HEADER', 'MAIN'], // wrappers (e.g., <nav id="TOC"> or <div id="TOC">)
27
+ // --- Constants and state -------------------------------------------
28
+
29
+ const
30
+ book = $$('h1').length > 1, // a document with multiple <h1> is a book (chapters)
31
+ // elements that are never broken across pages (CSS break-inside: avoid also works)
32
+ atomic = 'h1,h2,h3,h4,h5,h6,hr,img,svg,video,canvas,iframe,object,embed,math,mjx-container,figure,.figure,details',
33
+ // classes of the pieces of a broken element
11
34
  fr_cls = 'pagesjs-fragmented', fr_1 = 'fragment-first', fr_2 = 'fragment-last',
35
+ // pixels that the content may hang over the bottom of a page (the page has a
36
+ // much larger padding there), since sizes are rounded and the browsers differ
37
+ tol = 3,
38
+ // top/bottom page margin
12
39
  tb = ['top', 'bottom'].map(i =>
13
40
  parseFloat(getComputedStyle(d.documentElement).getPropertyValue(`--paper-margin-${i}`)) || 0
14
- ); // top/bottom page margin
41
+ ),
42
+ // the template of a page
43
+ tpl = d.createElement('div'),
44
+ boxes = [], // all pages
45
+ wrapped = new WeakSet(), // elements whose runs of inline nodes have been wrapped
46
+ hold = d.createElement('div'); // a hidden container for elements that need styles
15
47
  tpl.className = 'pagesjs-page';
16
48
  tpl.innerHTML = `<div class="pagesjs-header"></div>
17
49
  <div class="pagesjs-body"></div>
18
50
  <div class="pagesjs-footer"></div>`;
19
- let box, box_body, box_cls = [], H, H_min, h_code, l_code = [];
51
+ hold.style.display = 'none';
52
+
53
+ let
54
+ box, box_body, // the current page and its body
55
+ box_ctx, // where the content goes in the body (see ctx())
56
+ wrap = [], // the ancestors of the content root (outermost first)
57
+ H, B, // the height of a page and of its body
58
+ H_min, // the height of a single-line paragraph
59
+ main_title, // the title of the document
60
+ probed, // the content that is on the probe page (see probe())
61
+ pending, // the rest of the pagination, which is waiting for the probe
62
+ running, // the generator that does the rest of the pagination (see advance())
63
+ progress, n_done = 0, // the progress indicator and the number of finished pages
64
+ finished; // is the pagination finished?
65
+
66
+ // --- Page boxes ----------------------------------------------------
67
+
20
68
  function newPage(el) {
21
69
  el && !$('.pagesjs-body', el) && el.insertAdjacentHTML('afterbegin', tpl.innerHTML);
22
- box = el || tpl.cloneNode(true); box_body = box.children[1];
23
- box.classList.add(...box_cls);
70
+ box = el || tpl.cloneNode(true); box_body = box.children[1]; box_ctx = null;
24
71
  boxes.includes(box) || boxes.push(box); // store new pages in boxes
25
72
  return box;
26
73
  }
74
+ // The margin at the end of the content of a page is truncated at the end of the
75
+ // page (like in CSS fragmentation), so it should not count when the content is
76
+ // tested if it fits the page. It is the margin of the last element and its last
77
+ // descendants, until one with padding/border at the bottom.
78
+ function trailingMargin(body = box_body) {
79
+ let m = 0;
80
+ for (let e = body.lastElementChild; e; e = e.lastElementChild) {
81
+ const cs = getComputedStyle(e);
82
+ m = Math.max(m, parseFloat(cs.marginBottom) || 0);
83
+ if (parseFloat(cs.paddingBottom) || parseFloat(cs.borderBottomWidth)) break;
84
+ }
85
+ return m;
86
+ }
87
+ // the height of the page without the margin at the end of its content
88
+ function pageHeight() { return box.getBoundingClientRect().height - trailingMargin(); }
89
+ // does the page overflow?
90
+ function overflows() { return box.scrollHeight - trailingMargin() > H; }
27
91
  // start the next page and finish current page
28
92
  function nextPage(el, callback) {
29
93
  const cur = box; cur.after(newPage(el)); callback && callback(); finish(cur);
@@ -31,11 +95,51 @@
31
95
  // compute page numbers and temporarily remove the box
32
96
  function finish(box) {
33
97
  const h = box.scrollHeight;
34
- if (h > H && !box.dataset.pagesOffset) {
98
+ // tolerate a few pixels (and the margin of the last element) hanging over the page bottom
99
+ if (h - trailingMargin(box.children[1]) > H && !box.dataset.pagesOffset) {
35
100
  const n = calcPages(box, h);
36
101
  if (n > 1) box.dataset.pagesOffset = n;
37
102
  }
38
103
  box.remove();
104
+ progress && (progress.textContent = `Paginating: ${++n_done} pages done`);
105
+ }
106
+ // calculate how many new pages we need for overflowed content (this is just
107
+ // an estimate; if not accurate, use <div class="pagesjs-page" data-pages-offset="N">
108
+ // to provide a number manually)
109
+ function calcPages(box, h) {
110
+ let n = +box.dataset.pagesOffset;
111
+ if (n) return n;
112
+ n = Math.ceil(h/H);
113
+ if (n <= 1) return n;
114
+ // consider top/bottom page margin and table headers (which may be repeated on each page)
115
+ const m = tb.concat([...$$('thead', box)].map(el => +el.offsetHeight)).reduce((m1, m2) => m1 + m2);
116
+ if (!m) return n;
117
+ function nPages() { return Math.ceil((h + (n - 1) * m)/H); }
118
+ let n2 = nPages();
119
+ while (n2 > n) {
120
+ n = n2; n2 = nPages();
121
+ }
122
+ return n;
123
+ }
124
+
125
+ // chain of the ancestors of el (outermost first), excluding <body>
126
+ function ancestors(el) {
127
+ const a = [];
128
+ for (; el && el !== d.body; el = el.parentNode) a.unshift(el);
129
+ return a;
130
+ }
131
+ // The container for the content on the current page. It is a chain of empty
132
+ // clones of the content root and its ancestors (i.e., the original context), so
133
+ // CSS selectors that depend on them (e.g., `.body h2`) still apply on pages.
134
+ function ctx() {
135
+ if (!wrap.length) return box_body;
136
+ if (!box_ctx || !box_body.contains(box_ctx)) {
137
+ box_ctx = wrap.reduce((p, el) => {
138
+ const c = el.cloneNode(); c.classList.add('pagesjs-wrap');
139
+ return p.appendChild(c);
140
+ }, box_body);
141
+ }
142
+ return box_ctx;
39
143
  }
40
144
  function removeBlank(el) {
41
145
  if (!el || el.tagName === 'BODY') return false;
@@ -44,7 +148,10 @@
44
148
  v && el.remove();
45
149
  return v;
46
150
  }
47
- function fill(el) {
151
+
152
+ // --- Putting elements on pages -------------------------------------
153
+
154
+ function* fill(el) {
48
155
  // if the element is already a page, just use it as the box
49
156
  if (el.classList.contains('pagesjs-page')) {
50
157
  nextPage(el, () => nChild(el) > 3 && (
@@ -54,297 +161,407 @@
54
161
  nextPage() // create a new empty page
55
162
  ));
56
163
  } else {
57
- if (el.innerText.trim() && H - box.scrollHeight < H_min) nextPage();
58
- box_body.append(el);
59
- if (box.scrollHeight > H) {
60
- // temporarily remove el from DOM if it can be fragmented, otherwise
61
- // simply move it to the next page
62
- breakable(el) ? (el.tagName !== 'P' && el.remove(), fragment(el)) :
63
- nextPage(0, () => box_body.append(el));
164
+ // in a book, a chapter (a container of <h1>) starts on a new page
165
+ if (book && box.innerText !== '' && $('h1', el)) nextPage();
166
+ if (el.innerText.trim() && H - box.scrollHeight < H_min) breakPage();
167
+ yield* place(el);
168
+ }
169
+ }
170
+
171
+ // append el to the page, and if it overflows, put as much of it as possible on
172
+ // the page and the rest on the next page(s)
173
+ function* place(el) {
174
+ for (;;) {
175
+ const c = ctx();
176
+ endFrag(el);
177
+ if (isBigBlock(el)) {
178
+ // don't attach a big element to the page, since it takes time to style
179
+ // and lay out all its content just to find out that it does not fit
180
+ el = split(el, c, 'block');
64
181
  } else {
65
- // TODO: remove possibly duplicated citations: .citation + div > [id^="ref-"]
182
+ c.append(el);
183
+ if (!overflows()) return;
184
+ el = split(el, c);
66
185
  }
186
+ if (!el) return;
187
+ breakPage(el);
188
+ yield; // (a chance to paint the progress)
189
+ // TODO: remove possibly duplicated citations: .citation + div > [id^="ref-"]
67
190
  }
68
191
  }
69
- let fill_num; // record the number of lines filled last time
70
- function fillCode(el, i) {
71
- el.innerHTML = l_code.slice(0, i).join('\n');
72
- fill_num = i;
73
- }
74
- function breakable(el) {
75
- l_code = [];
76
- const t = el.tagName, c = el.firstElementChild;
77
- if (t === 'P' || fr_tag.includes(t)) return true;
78
- if (box_tag.includes(t)) {
79
- const cs = el.children;
80
- return (cs.length === 1 && fr_tag.includes(c?.tagName)) ||
81
- [...cs].filter(c => c.tagName === 'TABLE').length;
82
- }
83
- if (t !== 'PRE') return false;
84
- if (c?.tagName !== 'CODE') return false;
85
- // store all lines in l_code (TODO: ensure complete tags on each line)
86
- l_code = c.innerHTML.replace(/\n$/, '').split('\n');
87
- const n_code = l_code.length;
88
- if (n_code < 2) return false;
89
- h_code = c.offsetHeight / n_code; // approx line height
90
- c.innerHTML = ''; // temporarily empty <code>; will use l_code
91
- return true;
92
- }
93
- // break elements that are relatively easy to break (such as <ul>)
94
- function fragment(el, container, parent) {
95
- let cls = el.classList;
96
- const tag = el.tagName, frag = cls.contains(fr_cls);
97
- parent ? cls.add(fr_cls) : (frag ? cls.remove(fr_1) : cls.add(fr_cls, fr_1));
98
- let el2 = el.cloneNode(); // shallow clone (wrapper only)
99
- (container || box_body).append(el2);
100
- if (tag === 'P') {
101
- // fragmentation occurs in el instead of the clone el2, so swap them
102
- splitP(el, el2) || ([el, el2] = [el2, el], cls = el.classList);
103
- }
104
- const prev = el2.previousElementSibling || container?.previousElementSibling;
105
- function fragChildren(action) {
106
- for (let item of [...el.children]) {
107
- el2.append(item);
108
- if (box.scrollHeight > H) {
109
- action(item); break;
110
- }
111
- }
192
+
193
+ // Start a new page, but don't leave a heading alone at the bottom of the page.
194
+ // The heading may be the last child of a piece of a broken element (e.g., a
195
+ // chapter), in which case it goes back to the rest of the element (if provided).
196
+ function breakPage(rest) {
197
+ let parent = ctx(), h = parent.lastElementChild, depth = 0;
198
+ const isHeading = e => e?.matches('h1,h2,h3,h4,h5,h6');
199
+ while (rest && h && !isHeading(h) && h.classList.contains(fr_cls)) {
200
+ parent = h; h = h.lastElementChild; depth++;
112
201
  }
113
- if (box_tag.includes(tag)) {
114
- // fragment a wrapper's children (e.g., #TOC > ul)
115
- fragChildren(item => {
116
- // fragment item if it can be further fragmented, otherwise put it back
117
- el.prepend(item);
118
- fr_tag.includes(item.tagName) ? fragment(item, el2, el) : nChild(el2) && nextPage();
119
- });
120
- } else if (tag === 'PRE') {
121
- fragment(el.firstElementChild, el2, el);
122
- } else if (tag === 'CODE') {
123
- // split lines in <code> and try to move as many lines into el2 as possible
124
- const i = splitCode(el2);
125
- // i == 0 means not enough space to split code on current page
126
- i === fill_num || fillCode(el2, i); l_code.splice(0, i);
127
- if (i > 0) {
128
- l_code.join('').trim() === '' ? (l_code = []) : nextPage();
129
- }
130
- } else if (tag === 'TABLE') {
131
- // when el has no rows left and el2 is not empty, clear el
132
- const has_rows = splitTable(el, el2, prev);
133
- el2.innerHTML && (has_rows ? nextPage() : (el.innerHTML = ''));
202
+ const keep = isHeading(h) && hasPrev(h) && h;
203
+ keep && keep.remove();
204
+ nextPage();
205
+ if (!keep) return;
206
+ let target = rest; // the rest of the container of the heading
207
+ for (let i = 1; i < depth && target; i++) target = target.firstElementChild;
208
+ target?.tagName === parent.tagName && depth ? target.prepend(keep) : ctx().append(keep);
209
+ }
210
+ // Put as much of el (which has just overflowed the page in container) as
211
+ // possible into container, and return the rest (detached) if any. Unless el is
212
+ // the first thing on the page, it will be left out entirely if it can't be broken.
213
+ function split(el, container, kind) {
214
+ // (for a block, prev is determined after it is cut, to avoid laying it out)
215
+ const k = kind || kindOf(el), prev = k === 'block' ? undefined : hasPrev(el),
216
+ first = !el.classList.contains(fr_cls), r = k && splitters[k](el, container, prev, first);
217
+ if (!r) return prev && (el.remove(), el);
218
+ const [head, rest] = r;
219
+ if (blank(head)) return head.remove(), rest; // nothing fits
220
+ if (rest) {
221
+ rest.classList.add(fr_cls); rest.classList.remove(fr_1, fr_2);
134
222
  } else {
135
- // keep moving el's first item to el2 until page height > H
136
- fr_tag.slice(1).includes(tag) && fragChildren(item => {
137
- // move item back to el if the clone el2 is not the only element on page or has more than one child
138
- (prev || nChild(el2) > 1) && el.prepend(item);
139
- // update the start number of <ol> on next page
140
- tag === 'OL' && (el.start += nChild(el2));
141
- // don't open new page if el2 is empty (will open one below when testing el2_empty)
142
- nChild(el2) && nextPage();
143
- });
144
- }
145
- const el_empty = !l_code.length && removeBlank(el), el2_empty = removeBlank(el2);
146
- // add/remove the fragment-* class and exit if el has become empty
147
- if (el_empty) {
148
- const cls2 = el2.classList;
149
- if (parent) {
150
- container.classList.contains(fr_1) && cls2.remove(fr_cls);
151
- } else {
152
- cls2.contains(fr_1) ? cls2.remove(fr_cls, fr_1) : cls2.add(fr_2);
153
- }
154
- return;
223
+ head.classList.add(fr_2); // the last piece (also the first if it's not really split)
155
224
  }
156
- // if el2 is empty, it means nothing in el fits the box; we have to start a new box
157
- if (el2_empty) {
158
- cls.remove(fr_cls, fr_1); parent || nextPage();
225
+ return rest;
226
+ }
227
+
228
+ // is an element a block that is too big to be put on a page as a whole?
229
+ function isBigBlock(el) {
230
+ return !['TABLE', 'PRE'].includes(el.tagName) && el.getElementsByTagName('*').length > 300;
231
+ }
232
+ function blank(el) { return !el.firstElementChild && !el.textContent.trim(); }
233
+ // is there anything above el on the page (which means el may go to the next page)?
234
+ function hasPrev(el) {
235
+ for (; el && el !== box_body; el = el.parentNode)
236
+ for (let p = el.previousElementSibling; p; p = p.previousElementSibling)
237
+ if (p.getBoundingClientRect().height) return true;
238
+ return false;
239
+ }
240
+ function inFlow(cs) {
241
+ return cs.float === 'none' && !['absolute', 'fixed'].includes(cs.position);
242
+ }
243
+ // text, inline elements, and out-of-flow elements go with the text around them
244
+ function isInline(n) {
245
+ if (n.nodeType !== 1) return true;
246
+ const cs = getComputedStyle(n), v = cs.display;
247
+ return v.startsWith('inline') || v === 'none' || v === 'contents' || !inFlow(cs);
248
+ }
249
+ // is an element a part of the text (inline, and not a float, etc.)?
250
+ function inTextFlow(el) {
251
+ const cs = getComputedStyle(el);
252
+ return (cs.display.startsWith('inline') || cs.display === 'contents') && inFlow(cs);
253
+ }
254
+ // lines of <pre><code>; tags open at the end of a line (e.g., a multi-line
255
+ // comment) are closed there and reopened on the next line, so each line is balanced
256
+ function codeLines(pre) {
257
+ const open = [];
258
+ return pre.firstElementChild.innerHTML.replace(/\n$/, '').split('\n').map(line => {
259
+ const start = open.map(t => t[0]).join('');
260
+ line.replace(/<(\/?)([a-z][\w-]*)[^>]*>/gi, (m, c, t) => {
261
+ c ? open.pop() : open.push([m, t]);
262
+ });
263
+ return start + line + open.map(t => `</${t[1]}>`).reverse().join('');
264
+ });
265
+ }
266
+ // how can the element be broken: by 'block' (its child blocks), 'inline' (text
267
+ // lines), 'table' (rows), 'code' (lines), or not at all (undefined)?
268
+ function kindOf(el) {
269
+ const cs = getComputedStyle(el), t = el.tagName;
270
+ if (/avoid/.test(cs.breakInside) || el.matches(atomic)) return;
271
+ if (t === 'TABLE') return el.tBodies[0] && 'table';
272
+ if (!['block', 'list-item', 'flow-root'].includes(cs.display) || !inFlow(cs)) return;
273
+ if (t === 'PRE') {
274
+ if (el.firstElementChild?.tagName === 'CODE' && codeLines(el).length > 1) return 'code';
275
+ // wrapped long lines: move to the next page if it fits there, otherwise break by lines
276
+ if (el.offsetHeight <= B) return;
159
277
  }
160
- // keep fragmenting the remaining top-level el when el2 is not empty or not first element
161
- if ((!el2_empty || prev) && !parent) fragment(el);
278
+ return [...el.children].some(c => !isInline(c)) ? 'block' : 'inline';
162
279
  }
163
- // split table rows
164
- function splitTable(el, el2, prev) {
165
- const tb = el.tBodies[0], tb2 = tb.cloneNode(), rows = [...tb.rows], th = el.tHead;
166
- el2.append(tb2);
167
- // copy table header and footer
168
- [th, el.tFoot].forEach(t => t && el2.append(t.cloneNode(true)));
169
- for (let i = 0; i < rows.length; i++) {
170
- const row = rows[i];
171
- tb2.append(row);
172
- if (box.offsetHeight > H) {
173
- if (i > 0 || prev) tb.prepend(row);
174
- // clear the clone if current page can't fit even one row
175
- if (i === 0 && prev) el2.innerHTML = '';
176
- break;
280
+ function mark(el, first) {
281
+ el.classList.add(fr_cls); el.classList.remove(fr_2); first && el.classList.add(fr_1);
282
+ }
283
+ // pieces of a fragmented element that are put on a page as a whole are the last
284
+ // pieces; mark them (and their fragmented descendants) before measuring, since
285
+ // the size of the last piece is different (see pages.css); if it turns out to be
286
+ // too big and is split, the mark is removed
287
+ function endFrag(el) {
288
+ if (el.nodeType === 1) [el, ...$$('.' + fr_cls, el)].forEach(e => e.classList.contains(fr_cls) && e.classList.add(fr_2));
289
+ }
290
+ // shallow clone el (wrapper only) as the first piece of el in container
291
+ function cut(el, container, first) {
292
+ const head = el.cloneNode();
293
+ el.remove(); container.append(head); mark(head, first);
294
+ return head;
295
+ }
296
+ // wrap each run of inline nodes in a block (like an anonymous block box in CSS)
297
+ // so mixed content (e.g., <li>text<ul>...</ul></li>) can be broken as paragraphs
298
+ function wrapRuns(el) {
299
+ if (wrapped.has(el)) return;
300
+ wrapped.add(el);
301
+ // computed styles are available only in the DOM (but not necessarily on a page)
302
+ el.isConnected || hold.append(el);
303
+ let run = [];
304
+ function flush() {
305
+ if (run.some(n => n.nodeType === 1 || n.nodeType === 3 && n.nodeValue.trim())) {
306
+ const s = d.createElement('span');
307
+ s.className = 'pagesjs-run'; run[0].before(s); s.append(...run);
177
308
  }
309
+ run = [];
178
310
  }
179
- return tb.rows.length;
180
- }
181
- // figure out how many lines can fit the box via bisection
182
- function splitCode(el) {
183
- let i = i1 = 1, n = l_code.length, i2 = n + 2;
184
- const sols = []; // solutions tried
185
- while (i2 > i1 + 1) {
186
- fillCode(el, i);
187
- const delta = H - box.offsetHeight;
188
- if (delta === 0) return i;
189
- if (delta < 0) {
190
- if (i <= 1) return 0;
191
- i2 = i;
192
- } else {
193
- if (i >= n) return i;
194
- i1 = i;
311
+ for (const n of [...el.childNodes]) isInline(n) ? run.push(n) : flush();
312
+ flush();
313
+ el.parentNode === hold && el.remove();
314
+ }
315
+
316
+ const splitters = {block: splitBlock, inline: splitInline, table: splitTable, code: splitCode};
317
+
318
+ // --- Breaking elements ---------------------------------------------
319
+
320
+ // move children to a clone of el one by one until the page is full, and split
321
+ // the child that overflows recursively, so elements can be broken at any depth
322
+ function splitBlock(el, container, prev, first) {
323
+ wrapRuns(el);
324
+ const head = cut(el, container, first);
325
+ prev = hasPrev(head);
326
+ let item, partial;
327
+ while (item = el.firstChild) {
328
+ if (item.nodeType !== 1) { head.append(item); continue; }
329
+ endFrag(item);
330
+ const big = isBigBlock(item);
331
+ if (!big) {
332
+ head.append(item);
333
+ if (!overflows()) continue;
195
334
  }
196
- sols.push(i);
197
- // estimate the number of (more or less) lines needed
198
- const i3 = i + Math.round(delta / h_code);
199
- // if a solution has been tried, shorten step and (in/de)crement by 1
200
- i = sols.includes(i3) ? i + (delta > 0 ? 1 : -1) : i3;
201
- (delta > 0 && i >= n) && (i2 = n + 2, i = n); // solution may be n
335
+ const n = nChild(head), rest = split(item, head, big ? 'block' : undefined);
336
+ if (rest) { partial = nChild(head) > n; el.prepend(rest); break; }
202
337
  }
203
- return i1;
338
+ prev && !partial && moveShortHead(head, el);
339
+ blank(el) && fitLastPiece(head, el, prev);
340
+ el.tagName === 'OL' && nChild(head) && !blank(el) && fixOlStart(head, el);
341
+ return [head, blank(el) ? null : el];
342
+ }
343
+
344
+ // if only about one line (e.g., a legend or the first list item) is left on the
345
+ // page, and no child was split, move it to the next page with the rest (el)
346
+ function moveShortHead(head, el) {
347
+ if (!blank(el) && head.getBoundingClientRect().height < 1.5 * H_min)
348
+ el.prepend(...head.childNodes);
349
+ }
350
+ // If all children fit, head is the last piece, which has bottom margin/padding/
351
+ // border that were hidden when it was measured as a non-last piece; push the
352
+ // last children out (into el) if it is too big now.
353
+ function fitLastPiece(head, el, prev) {
354
+ head.classList.add(fr_2);
355
+ while (overflows() && head.lastElementChild && (nChild(head) > 1 || prev))
356
+ el.prepend(head.lastElementChild);
357
+ blank(el) || head.classList.remove(fr_2);
358
+ }
359
+ // update the start number of the rest of <ol> (an item split in half counts once)
360
+ function fixOlStart(head, el) {
361
+ el.start += nChild(head) - (el.firstElementChild.classList.contains(fr_cls) ? 1 : 0);
204
362
  }
205
363
  // split <p> by testing if a range fits the current box
206
- function splitP(el, el2) {
207
- if (!el.parentNode) {
208
- box_body.append(el); // move el into DOM to measure chars if removed
209
- // see if we don't need to split it now
210
- if (box.scrollHeight <= H) return;
364
+ function splitInline(el, container, prev, first) {
365
+ const ends = lineStarts(el);
366
+ if (ends.length < 2) return; // single-line paragraph
367
+ const r = d.createRange(), rest = el.cloneNode(), n = ends.length;
368
+ let k = n; // number of lines left in el
369
+ function cutLine() {
370
+ const loc = ends[--k];
371
+ loc.i < 0 ? r.setStartBefore(loc.node) : r.setStart(loc.node, loc.i);
372
+ r.setEnd(el, el.childNodes.length);
373
+ rest.prepend(r.extractContents());
374
+ const last = el.lastChild; // strip trailing empty tags left by range extraction
375
+ last?.innerHTML === '' && last.remove();
376
+ }
377
+ mark(el, first);
378
+ // remove lines from the end of paragraph (but keep the first line if el is
379
+ // the first thing on the page)
380
+ while (k > (prev ? 0 : 1)) {
381
+ cutLine();
382
+ if (k > 0 && !overflows()) break;
211
383
  }
384
+ // avoid a widow (single last line on the next page) and an orphan (single
385
+ // first line at the bottom of the page)
386
+ if (k > 1 && n - k === 1) cutLine();
387
+ if (k === 1 && prev && n < 5) cutLine(); // (not for a long paragraph, to avoid moving too much)
388
+ return [el, rest];
389
+ }
390
+
391
+ // find the break position of each line (exclude block elements like footnotes)
392
+ function lineStarts(el) {
212
393
  const r = d.createRange(), ends = [{node: el, i: 0}];
213
- // find the break position of each line (exclude block elements like footnotes)
214
394
  const walker = d.createTreeWalker(el, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
215
395
  let node, prev;
216
- function collectEnds(el, i) {
217
- const rect = el.getBoundingClientRect();
218
- // if the previous el is at top-right of current el, assume line
219
- // ends before current el (TODO: how about RTL languages?)
220
- prev && prev.bottom <= rect.top && prev.right > rect.left && ends.push({node, i});
221
- prev = rect;
396
+ // if the previous rect is at top-right of current rect, assume a line ends
397
+ // before the current one (TODO: how about RTL languages?)
398
+ function newLine(rect) {
399
+ return prev && prev.bottom <= rect.top && prev.right > rect.left;
222
400
  }
223
401
  while (node = walker.nextNode()) {
224
402
  const t = node.tagName;
225
403
  if (t) {
226
- if (['DIV', 'MJX-CONTAINER'].includes(t) || (t === 'SPAN' && $('.katex', node))) {
227
- node = walker.nextSibling(); // skip DIVs (footnotes) and math
404
+ if (t === 'MJX-CONTAINER' || (t === 'SPAN' && $('.katex', node)) || !inTextFlow(node)) {
405
+ node = walker.nextSibling(); // skip blocks and floats (footnotes) and math
228
406
  if (!node) break;
229
407
  }
230
408
  if (node.firstChild) continue; // for element nodes, traverse to bottom
231
409
  }
232
410
  if (node.tagName) {
233
- collectEnds(node, -1);
234
- } else {
235
- const txt = node.textContent;
236
- if (txt.trim()) for (let i = 0; i < txt.length; i++) {
237
- r.setStart(node, i); r.setEnd(node, i + 1); collectEnds(r, i);
238
- }
411
+ const rect = node.getBoundingClientRect();
412
+ newLine(rect) && ends.push({node, i: -1});
413
+ prev = rect;
414
+ } else if (node.textContent.trim()) {
415
+ // a text node has one rect per line, and a new line starts at the first
416
+ // character that makes the range of the text have one more rect
417
+ r.selectNodeContents(node);
418
+ const rects = r.getClientRects();
419
+ if (!rects.length) continue;
420
+ newLine(rects[0]) && ends.push({node, i: 0});
421
+ for (let k = 1; k < rects.length; k++) ends.push({node, i: lineOffset(node, k, r)});
422
+ prev = rects[rects.length - 1];
239
423
  }
240
424
  }
241
- if (ends.length < 2) {
242
- el.remove(); return 1; // single-line paragraph
425
+ return ends;
426
+ }
427
+ // the offset of the first character on the k-th line of a text node (via bisection)
428
+ function lineOffset(node, k, r) {
429
+ let lo = 0, hi = node.length;
430
+ while (lo < hi) {
431
+ const mid = (lo + hi) >> 1;
432
+ r.setStart(node, 0); r.setEnd(node, mid);
433
+ r.getClientRects().length > k ? hi = mid : lo = mid + 1;
243
434
  }
244
- el2.remove();
245
- // remove lines from the end of paragraph
246
- for (let i = ends.length - 1; i >= 0; i--) {
247
- const loc = ends[i];
248
- loc.i < 0 ? r.setStartBefore(loc.node) : r.setStart(loc.node, loc.i);
249
- r.setEnd(el, el.childNodes.length);
250
- el2.prepend(r.extractContents());
251
- const last = el.lastChild; // strip trailing empty tags left by range extraction
252
- last?.innerHTML === '' && last.remove();
253
- if (i > 0 && box.scrollHeight <= H) {
254
- nextPage(); break;
435
+ return lo - 1; // (the range ends after the first character of the line)
436
+ }
437
+ // split table rows
438
+ function splitTable(el, container, prev, first) {
439
+ const head = cut(el, container, first), tb = el.tBodies[0], tb2 = tb.cloneNode(),
440
+ rows = [...tb.rows], n = rows.length, min = prev ? 0 : 1;
441
+ head.append(tb2);
442
+ // copy table header and footer
443
+ [el.tHead, el.tFoot].forEach(t => t && head.append(t.cloneNode(true)));
444
+ // Put all rows in the page and lay them out once. The rows whose bottoms are
445
+ // below (the bottom of the last row - the overflow) do not fit; put them back.
446
+ tb2.append(...rows);
447
+ const over = pageHeight() - H - .5; // (see fitLines())
448
+ if (over >= 0) {
449
+ const limit = rows[n - 1].getBoundingClientRect().bottom - over;
450
+ let lo = 0, hi = n; // the first row that is below the limit (by bisection)
451
+ while (lo < hi) {
452
+ const mid = (lo + hi) >> 1;
453
+ rows[mid].getBoundingClientRect().bottom <= limit ? lo = mid + 1 : hi = mid;
255
454
  }
455
+ let k = Math.max(lo, min);
456
+ tb.prepend(...rows.slice(k));
457
+ while (k > min && pageHeight() > H + .5) tb.prepend(rows[--k]); // make sure they fit
458
+ }
459
+ // clear the clone if current page can't fit even one row
460
+ tb2.rows.length || (head.innerHTML = '');
461
+ // avoid a single row on either page
462
+ const m = tb2.rows.length;
463
+ if (tb.rows.length === 1 && m > 1 || m === 1 && prev && tb.rows.length) {
464
+ tb.prepend(tb2.rows[m - 1]);
465
+ if (m === 1) head.innerHTML = '';
256
466
  }
467
+ return [head, tb.rows.length ? el : null];
257
468
  }
258
-
259
- // use data-short-title of a header if exists, and fall back to inner text
260
- function shortTitle(h) {
261
- return h && (h.dataset.shortTitle || h.innerText);
469
+ // split lines in <code> and move as many lines into the clone as possible
470
+ function splitCode(el, container, prev, first) {
471
+ const code = el.firstElementChild, lines = codeLines(el);
472
+ // other children go to the first piece, except those after <code> in the normal
473
+ // flow (e.g., a link to the output), which go to the last piece
474
+ const kids = [...el.children], tail = kids.filter((c, j) => j > kids.indexOf(code) && inFlow(getComputedStyle(c)));
475
+ const head = cut(el, container, first), code2 = code.cloneNode();
476
+ head.append(code2, ...kids.filter(c => c !== code && !tail.includes(c)));
477
+ let i = fitLines(code2, lines, prev);
478
+ // avoid a single line on either page
479
+ if (i > 1 && lines.length - i === 1) i--;
480
+ if (i === 1 && prev) i = 0;
481
+ // i == 0 means not enough space to split code on current page
482
+ if (i) code2.innerHTML = lines.slice(0, i).join('\n'); else head.innerHTML = '';
483
+ code.innerHTML = lines.slice(i).join('\n');
484
+ if (code.innerHTML.trim()) return [head, el];
485
+ i && head.append(...tail);
486
+ return [head, null];
262
487
  }
263
- const main = shortTitle($('h1.title, .frontmatter h1, .title, h1')), // main title
264
- ps = (book ? 'h1' : 'h2') + ':not(.frontmatter *)'; // page title selector
265
-
266
- // calculate how many new pages we need for overflowed content (this is just
267
- // an estimate; if not accurate, use <div class="pagesjs-page" data-pages-offset="N">
268
- // to provide a number manually)
269
- function calcPages(box, h) {
270
- let n = +box.dataset.pagesOffset;
271
- if (n) return n;
272
- n = Math.ceil(h/H);
273
- if (n <= 1) return n;
274
- // consider top/bottom page margin and table headers (which may be repeated on each page)
275
- const m = tb.concat([...$$('thead', box)].map(el => +el.offsetHeight)).reduce((m1, m2) => m1 + m2);
276
- if (!m) return n;
277
- function nPages() { return Math.ceil((h + (n - 1) * m)/H); }
278
- let n2 = nPages();
279
- while (n2 > n) {
280
- n = n2; n2 = nPages();
488
+ // Figure out how many lines can fit the box. Instead of guessing and testing
489
+ // different numbers of lines, put all lines in <code> and lay them out once, and
490
+ // read the positions of the line breaks, which tells how many lines are below
491
+ // the bottom of the page. (Lines are balanced, so their line breaks are in the
492
+ // text nodes that are children of <code>.)
493
+ function fitLines(code, lines, prev) {
494
+ const n = lines.length, min = prev ? 0 : 1;
495
+ code.innerHTML = lines.join('\n');
496
+ // (the page fits if its height is rounded to H or less, i.e., it is < H + .5)
497
+ const over = pageHeight() - H - .5;
498
+ if (over < 0) return n;
499
+ const r = d.createRange(), bottoms = []; // the bottom of each line
500
+ code.childNodes.forEach(node => {
501
+ if (node.nodeType !== 3) return;
502
+ for (let i = node.data.indexOf('\n'); i >= 0; i = node.data.indexOf('\n', i + 1)) {
503
+ r.setStart(node, i); r.setEnd(node, i + 1);
504
+ bottoms.push(r.getBoundingClientRect().bottom);
505
+ }
506
+ });
507
+ // the bottom of the last line (which has no line break), and the space after it
508
+ r.selectNodeContents(code);
509
+ const rects = r.getClientRects(), last = rects[rects.length - 1].bottom;
510
+ bottoms.push(last);
511
+ // the lines whose bottoms are not below (the bottom of the last line - over)
512
+ let i = 0;
513
+ while (i < n && bottoms[i] <= last - over) i++;
514
+ // blank lines at the end don't take space, so don't leave them to the next page
515
+ while (i && i < n && !lines[i].trim()) i++;
516
+ code.innerHTML = lines.slice(0, Math.max(i, min)).join('\n');
517
+ // make sure that the lines fit (e.g., when the line break is not at the bottom
518
+ // of a line)
519
+ while (i > min && pageHeight() > H + .5) {
520
+ code.innerHTML = lines.slice(0, --i).join('\n');
281
521
  }
282
- return n;
522
+ return Math.max(i, min);
283
523
  }
284
524
 
285
- function paginate() {
286
- // we need to wait for all resources to be fully loaded before paginating
287
- if (d.readyState !== 'complete') return addEventListener('load', paginate);
525
+ // --- Letting content settle before measuring it --------------------
288
526
 
289
- const cls = d.body.classList;
290
- if (cls.contains('pagesjs')) return; // already paginated
291
- dispatchEvent(new Event('pagesjs:before'));
292
-
293
- cls.add('pagesjs');
294
- d.body.insertAdjacentElement('afterbegin', newPage());
295
- H = box.clientHeight || window.innerHeight; // use window height if box height not specified
296
-
297
- // remove possible classes on TOC/footnotes that we don't need for printing
298
- $$(':is(#TOC, .footnotes, .chapter-before, .chapter-after):is(.side-left, .side-right).side').forEach(el => {
299
- el.classList.remove('side', 'side-left', 'side-right');
527
+ // Let content that reacts to the width of its container (e.g., diagrams that use
528
+ // a ResizeObserver) settle at the page width before measuring anything: put all
529
+ // content on a probe page and wait for a few frames.
530
+ function probe(roots, els) {
531
+ box.classList.add('pagesjs-settle');
532
+ roots.forEach((el, i) => {
533
+ wrap = ancestors(el); box_ctx = null; ctx().append(...els[i]);
300
534
  });
301
-
302
- cls.add('pagesjs-filling');
303
-
304
- // test how much space a single-line paragraph needs
305
- const p = d.createElement('p'), H0 = box.scrollHeight;
306
- p.innerText = 'A'; box_body.append(p);
307
- H_min = box.scrollHeight - H0; p.remove();
308
-
309
- // add dot leaders to TOC
310
- $$('#TOC a[href^="#"]').forEach(a => {
311
- const s = d.createElement('span'); // move TOC item content into a span
312
- s.className = 'toc-text'; a.append(s);
313
- let c; while (c = s.previousSibling) {
314
- // exclude section number spans
315
- if (c.classList?.contains('section-number')) break; s.prepend(c);
316
- }
317
- a.dataset.pageNumber = '000'; // placeholder for page numbers
535
+ probed = els;
536
+ return new Promise(done => {
537
+ const t = setTimeout(done, 500); // rAF doesn't run in background tabs
538
+ let n = 0;
539
+ (function tick() {
540
+ requestAnimationFrame(() => ++n < 3 ? tick() : (clearTimeout(t), done()));
541
+ })();
318
542
  });
543
+ }
544
+ function unprobe() {
545
+ if (!probed) return;
546
+ probed.forEach(ch => ch.forEach(el => el.remove()));
547
+ box_body.innerHTML = ''; box_ctx = null; wrap = [];
548
+ box.classList.remove('pagesjs-settle');
549
+ probed = null;
550
+ }
319
551
 
320
- // temporarily move all elements out of DOM (to speed up rendering single pages)
321
- const els = [];
322
- $$('.body').forEach(el => {
323
- // move <style>/<link> into <head> so styles can be applied globally
324
- const ch = [...el.children]
325
- .filter(el => !['STYLE', 'LINK'].includes(el.tagName) || d.body.prepend(el));
326
- els.push(ch); ch.forEach(el => el.remove());
327
- });
328
- // iteratively add elements to pages
329
- $$('.frontmatter, .abstract, #TOC:not(.chapter-toc)').forEach(el => {
330
- (fill(el), book && nextPage());
331
- });
332
- $$('.body').forEach((el, i) => {
333
- // preserve book chapter classes if exist
334
- box_cls = ['chapter', 'appendix'].filter(i => el.classList.contains(i));
335
- book && (box.innerText === '' ? newPage(box) : nextPage());
336
- els[i].forEach(fill);
337
- // clean up container and self if empty
338
- removeBlank(el.parentNode); removeBlank(el);
339
- });
340
- finish(box); // finish the last box
341
- cls.remove('pagesjs-filling');
552
+ // --- Page numbers and titles ---------------------------------------
342
553
 
343
- // add page number, title, etc. to data-* attributes of page elements
554
+ // use data-short-title of a header if exists, and fall back to inner text
555
+ function shortTitle(h) {
556
+ return h && (h.dataset.shortTitle || h.innerText);
557
+ }
558
+ const ps = (book ? 'h1' : 'h2') + ':not(.pagesjs-front *)'; // page title selector
559
+ // add page number, title, etc. to data-* attributes of page elements
560
+ function numberPages() {
344
561
  let page_title, i = 0;
345
562
  boxes.forEach(box => {
346
563
  if (book) {
347
- if ($('.frontmatter', box)) return; // skip book frontmatter page
564
+ if ($('.pagesjs-front', box)) return; // skip book frontmatter page
348
565
  $(ps, box) && (page_title = ''); // empty title for first page of chapter
349
566
  }
350
567
  const N = +box.dataset.pagesOffset || 1;
@@ -352,7 +569,7 @@
352
569
  i += N;
353
570
  box.classList.add(`page-${i % 2 === 0 ? 'even' : 'odd'}`);
354
571
  const info = {
355
- 'pageNumber': i, 'mainTitle': main, 'pageTitle': page_title
572
+ 'pageNumber': i, 'mainTitle': main_title, 'pageTitle': page_title
356
573
  };
357
574
  [box.children[0], box.children[2]].forEach(el => {
358
575
  for (const key in info) info[key] && (el.dataset[key] = info[key]);
@@ -365,19 +582,158 @@
365
582
  i === 0 ? (ft = el, box.children[1].after(el)) : (ft.append(...el.children), el.remove());
366
583
  });
367
584
  });
585
+ }
368
586
 
369
- // unhide all pages
370
- d.body.prepend(...boxes);
371
-
372
- // add page numbers to TOC with data-* attributes
587
+ // add page numbers to TOC with data-* attributes
588
+ function numberToc() {
373
589
  $$('#TOC a[href^="#"]').forEach(a => {
374
590
  const id = CSS.escape(a.getAttribute('href').replace(/^#/, '')),
375
591
  p = $(`.pagesjs-page:has(#${id}) .pagesjs-header`);
376
592
  a.dataset.pageNumber = p ? p.dataset.pageNumber : '';
377
593
  });
378
- dispatchEvent(new Event('pagesjs:after'));
379
594
  }
380
- addEventListener('beforeprint', paginate);
595
+
596
+ // --- Pagination ----------------------------------------------------
597
+
598
+ // The content root is specified via <body data-pages-root="selector">, or is
599
+ // <main> (or an element with role="main"), or the top-level <article> elements,
600
+ // or <body>. Everything else (e.g., navigation bars) will be hidden.
601
+ function findRoots() {
602
+ const sel = d.body.dataset.pagesRoot, x = sel ? [...$$(sel)] : [];
603
+ if (x.length) return x;
604
+ const main = $('main, [role="main"]');
605
+ if (main) return [main];
606
+ const articles = [...$$('article')].filter(el => !el.parentNode.closest('article'));
607
+ return articles.length ? articles : [d.body];
608
+ }
609
+ // The frontmatter (title, author, etc.) of the document is <header> (a child of
610
+ // <body>) by default, or specified via <body data-pages-front="selector">; it is
611
+ // put on its own page in a book.
612
+ function markFrontmatter() {
613
+ $$(d.body.dataset.pagesFront || 'body > header').forEach(el => el.classList.add('pagesjs-front'));
614
+ }
615
+ // remove the classes of the TOC, footnotes, etc. that put them in the margin on
616
+ // screen but are not suitable for printing
617
+ function removeSideClasses() {
618
+ $$(':is(#TOC, .footnotes, .chapter-before, .chapter-after):is(.side-left, .side-right).side').forEach(el => {
619
+ el.classList.remove('side', 'side-left', 'side-right');
620
+ });
621
+ }
622
+ // test how much space a single-line paragraph needs
623
+ function measureMinHeight() {
624
+ const p = d.createElement('p'), H0 = box.scrollHeight;
625
+ p.innerText = 'A'; box_body.append(p);
626
+ H_min = box.scrollHeight - H0; p.remove();
627
+ }
628
+ // add dot leaders to TOC (page numbers will be added after the pages are ready)
629
+ function addTocLeaders() {
630
+ $$('#TOC a[href^="#"]').forEach(a => {
631
+ const s = d.createElement('span'); // move TOC item content into a span
632
+ s.className = 'toc-text'; a.append(s);
633
+ let c; while (c = s.previousSibling) {
634
+ // exclude section number spans
635
+ if (c.classList?.contains('section-number')) break; s.prepend(c);
636
+ }
637
+ a.dataset.pageNumber = '000'; // placeholder for page numbers
638
+ });
639
+ }
640
+ // take the children of the roots out of the DOM (to speed up rendering single
641
+ // pages), and return them
642
+ function detachContent(roots) {
643
+ return roots.map(el => {
644
+ // move <style>/<link> into <head> so styles can be applied globally (not
645
+ // only when they are in the DOM), no matter how deeply they are nested
646
+ $$('style, link[rel="stylesheet"]', el).forEach(el => d.head.append(el));
647
+ const ch = [...el.children].filter(el => ![box, hold, progress].includes(el) &&
648
+ !['SCRIPT', 'NOSCRIPT', 'TEMPLATE'].includes(el.tagName));
649
+ ch.forEach(el => el.remove());
650
+ return ch;
651
+ });
652
+ }
653
+ // iteratively add elements to pages
654
+ function* fillPages(roots, els) {
655
+ for (const el of $$('.pagesjs-front, .abstract, #TOC:not(.chapter-toc)')) {
656
+ yield* fill(el);
657
+ book && nextPage();
658
+ }
659
+ for (const [i, el] of roots.entries()) {
660
+ wrap = ancestors(el); box_ctx = null;
661
+ book && (box.innerText === '' ? newPage(box) : nextPage());
662
+ for (const child of els[i]) yield* fill(child);
663
+ // clean up container and self if empty
664
+ removeBlank(el.parentNode); removeBlank(el);
665
+ }
666
+ finish(box); // finish the last box
667
+ // unwrap the blocks created for runs of inline nodes
668
+ $$('.pagesjs-run').forEach(el => el.replaceWith(...el.childNodes));
669
+ }
670
+ // Run the rest of the pagination. If it is not sync, do it in slices of 0.5s,
671
+ // so the browser can show the progress in between (not too often, to save time).
672
+ function advance(sync) {
673
+ const t = performance.now();
674
+ while (!running.next().done) {
675
+ if (sync || performance.now() - t < 500) continue;
676
+ return new Promise(go => { requestAnimationFrame(go); setTimeout(go, 50); })
677
+ .then(() => advance());
678
+ }
679
+ }
680
+ function paginate(sync) {
681
+ // nobody sees the progress in a headless browser (and printing has to be sync)
682
+ const quiet = sync || /Headless/.test(navigator.userAgent) || navigator.webdriver;
683
+ // we need to wait for all resources to be fully loaded before paginating
684
+ if (d.readyState !== 'complete') return addEventListener('load', () => paginate(sync));
685
+
686
+ const cls = d.body.classList;
687
+ if (cls.contains('pagesjs')) return; // already paginated
688
+ dispatchEvent(new Event('pagesjs:before'));
689
+
690
+ markFrontmatter();
691
+ // (get the title while the document is visible, so innerText works)
692
+ main_title = shortTitle($('h1.title, .pagesjs-front h1, .title, h1'));
693
+
694
+ cls.add('pagesjs');
695
+ d.body.append(hold);
696
+ if (!quiet) { // a simple indicator to tell users to wait
697
+ progress = d.createElement('div');
698
+ progress.className = 'pagesjs-progress';
699
+ progress.textContent = 'Paginating...';
700
+ d.body.append(progress);
701
+ }
702
+ d.body.insertAdjacentElement('afterbegin', newPage());
703
+ H = (box.clientHeight || window.innerHeight) + tol; B = box_body.clientHeight || H; // use window height if box height not specified
704
+ removeSideClasses();
705
+ cls.add('pagesjs-filling');
706
+ measureMinHeight();
707
+ addTocLeaders();
708
+
709
+ const roots = findRoots(), els = detachContent(roots);
710
+ function* run() {
711
+ yield* fillPages(roots, els);
712
+ cls.remove('pagesjs-filling');
713
+ numberPages();
714
+ d.body.prepend(...boxes); // unhide all pages
715
+ numberToc();
716
+ hold.remove(); progress?.remove();
717
+ finished = true;
718
+ dispatchEvent(new Event('pagesjs:after'));
719
+ }
720
+ // Pagination is async unless it has to be sync (beforeprint). If printing
721
+ // starts while it's pending (e.g., headless printing right after the page is
722
+ // loaded), finish it right away.
723
+ pending = sync => { pending = null; unprobe(); running = run(); return advance(sync || quiet); };
724
+ sync ? pending(true) : probe(roots, els).then(() => pending?.());
725
+ }
726
+ addEventListener('beforeprint', () => {
727
+ if (pending) pending(true);
728
+ else if (running) while (!running.next().done); // finish the pagination in progress
729
+ else paginate(true);
730
+ });
731
+ // A script that controls the browser can request the pagination by dispatching
732
+ // pagesjs:paginate, and wait for pagesjs:after (which is also dispatched if the
733
+ // pagination was already finished)
734
+ addEventListener('pagesjs:paginate', () => {
735
+ finished ? dispatchEvent(new Event('pagesjs:after')) : paginate();
736
+ });
381
737
  // use query param ?paged=1 to indicate pagination (press p to toggle)
382
738
  const SP = new URLSearchParams(location.search);
383
739
  SP.get('paged') && paginate();