@xiee/utils 1.14.126 → 1.14.127

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