@xiee/utils 1.14.154 → 1.14.156

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,36 +1,24 @@
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.
1
+ // Paginate an HTML page into page boxes (e.g., A4) so each holds as much content as fits.
3
2
  //
4
- // How it works:
5
- // 1. The content root (e.g., <main>) is emptied, and all its content is laid out
6
- // once on a probe page (probe()), so that content that reacts to the page width
7
- // settles and the positions of the blocks are known.
8
- // 2. The children are put on pages one by one (fill() -> place()). Only the current
9
- // page is in the DOM, so measuring it is cheap (box.scrollHeight > H means the
10
- // page overflows), but each measurement is a forced layout; so children that
11
- // surely fit, according to their positions on the probe page, are put on a page
12
- // together and measured once (fitting()).
13
- // 3. When an element makes the page overflow, split() puts as much of it as
14
- // possible on the current page and returns the rest, which goes to the next
15
- // page. An element can be broken in different ways (kindOf()): block elements
16
- // (e.g., lists and quotes) are cloned and their children are moved into the
17
- // clone as in step 2, with the child that overflows broken recursively; text,
18
- // table rows, and code lines are broken by lines/rows. Every piece of a broken
19
- // element has the classes pagesjs-fragmented, fragment-first, fragment-last
20
- // (the pieces can be styled differently in pages.css).
21
- // A float (see isFloat()) that does not fit is not broken: it waits for the next
22
- // page (class pagesjs-waited), and the content after it fills the space. A float
23
- // that is very tall takes a whole page (nothing else fits on it), centered. So does
24
- // an element with the class pagesjs-wide (e.g., a table with many columns), on a
25
- // landscape page (class page-wide, see takePage()).
26
- // 4. Each page contains empty copies of the ancestors of the content root, so
27
- // CSS selectors that depend on them still work (see ctx()).
28
- // 5. In the end, page numbers and titles are added to the headers/footers.
3
+ // 1. The content root (e.g., <main>) is emptied and laid out once on a probe page, so
4
+ // width-dependent content settles and block positions are known (probe()).
5
+ // 2. Children go onto pages one by one (fill() -> place()). Only the current page is in
6
+ // the DOM; children that surely fit by their probe positions are measured together (fitting()).
7
+ // 3. When an element overflows, split() puts as much as possible on the page, the rest on the
8
+ // next. kindOf() decides how: blocks are cloned and their children moved (recursively);
9
+ // text, table rows, and code lines are broken by lines/rows. Pieces get the classes
10
+ // pagesjs-fragmented, fragment-first, fragment-last (styled in pages.css).
11
+ // Floats (isFloat()) are never broken: one that does not fit waits for the next page
12
+ // (pagesjs-waited) while later content fills the gap. A tall float takes a page alone,
13
+ // and a wide one (.pagesjs-wide) a landscape page (takePage()).
14
+ // 4. Each page holds empty clones of the ancestors of the content root, so CSS selectors
15
+ // that depend on them still match (ctx()).
16
+ // 5. In the end, page numbers and titles go into data-* attributes for the headers/footers.
29
17
  (d => {
30
18
 
31
19
  // --- Utilities -----------------------------------------------------
32
20
 
33
- function $(s, el = d) { return el?.querySelector(s); }
21
+ function $(s, el = d) { return el?.querySelector(s); }
34
22
  function $$(s, el = d) { return el ? el.querySelectorAll(s) : []; }
35
23
  function nChild(el) { return el.childElementCount; }
36
24
  function kids(el) { return [...el.children]; }
@@ -54,31 +42,27 @@
54
42
  // --- Constants and state -------------------------------------------
55
43
 
56
44
  const
57
- book = $$('h1').length > 1, // a document with multiple <h1> is a book (chapters)
58
- // elements that are never broken across pages (CSS break-inside: avoid also works)
45
+ book = $$('h1').length > 1, // several <h1>: a book, whose chapters start on new pages
46
+ // never broken across pages (CSS break-inside: avoid also works)
59
47
  atomic = 'h1,h2,h3,h4,h5,h6,hr,img,svg,video,canvas,iframe,object,embed,math,mjx-container,figure,.figure,.pagesjs-float,.pagesjs-wide,.caption,details',
60
- // classes of the pieces of a broken element
61
48
  fr_cls = 'pagesjs-fragmented', fr_1 = 'fragment-first', fr_2 = 'fragment-last',
62
- // pixels that the content may hang over the bottom of a page (the page has a
63
- // much larger padding there), since sizes are rounded and the browsers differ
49
+ // px that content may hang over the page bottom (the page has more padding there;
50
+ // browsers round sizes differently)
64
51
  tol = 3,
65
- // floats taller than this percentage of the page body take a whole page (see stays());
66
- // set via <body data-pages-float-page="...">, e.g., 100 for never (in LaTeX, a float
67
- // taller than 70% of the page, \topfraction, can't share a page with text at its top)
52
+ // floats taller than this % of the body take a page (<body data-pages-float-page="...">;
53
+ // 100 for never)
68
54
  floatPage = parseFloat(d.body.dataset.pagesFloatPage) || 70,
69
- // top/bottom page margin
70
55
  tb = ['top', 'bottom'].map(i =>
71
56
  num(style(d.documentElement).getPropertyValue(`--paper-margin-${i}`))
72
- ),
73
- // the template of a page
57
+ ), // top/bottom page margin
74
58
  tpl = make('div', 'pagesjs-page'),
75
59
  boxes = [], // all pages
76
- wrapped = new WeakSet(), // elements whose runs of inline nodes have been wrapped
77
- guessed = new WeakSet(), // pages whose number of physical pages is an estimate (see calcPages())
78
- floats = [], // the floats that wait for a page (see putFloats())
79
- notes = new Map(), // the items of each note (footnote or citation), by its marker (see detachNotes())
80
- probeY = new WeakMap(), // the bottoms of the blocks on the probe page (see fitting())
81
- hold = make('div'); // a hidden container for elements that need styles
60
+ wrapped = new WeakSet(), // elements whose inline runs are wrapped (wrapRuns())
61
+ guessed = new WeakSet(), // pages whose number of physical pages is estimated (calcPages())
62
+ floats = [], // floats waiting for a page (putFloats())
63
+ notes = new Map(), // items of each note (footnote or citation), by its marker (detachNotes())
64
+ probeY = new WeakMap(), // bottoms of the blocks on the probe page (fitting())
65
+ hold = make('div'); // hidden container for elements that need styles
82
66
  tpl.innerHTML = `<div class="pagesjs-header"></div>
83
67
  <div class="pagesjs-body"></div>
84
68
  <div class="pagesjs-footer"></div>`;
@@ -86,23 +70,25 @@
86
70
 
87
71
  let
88
72
  box, box_body, // the current page and its body
89
- box_ctx, // where the content goes in the body (see ctx())
73
+ box_ctx, // where the content goes in the body (ctx())
90
74
  wrap = [], // the ancestors of the content root (outermost first)
91
75
  H, B, // the height of the current page and of its body
92
- portrait, landscape, // [H, B] of a normal page and of a landscape page (see takePage())
76
+ portrait, landscape, // [H, B] of a normal page and of a landscape page (takePage())
93
77
  H_min, H_line, // the height of a single-line paragraph (with margins) and of a line
94
- used, // the height of the content of the page when it was last measured (see overflows())
95
- whole, // the float that takes the page that is being filled (see takePage())
78
+ used, // the content height of the page when it was last measured (overflows())
79
+ whole, // the float that takes the page being filled (takePage())
96
80
  main_title, // the title of the document
97
- probed, // the content that is on the probe page (see probe())
98
- pending, // the rest of the pagination, which is waiting for the probe
99
- running, // the generator that does the rest of the pagination (see advance())
81
+ probed, // the content on the probe page (probe())
82
+ pending, // the rest of the pagination, waiting for the probe
83
+ running, // the generator that does the rest of the pagination (advance())
100
84
  progress, n_done = 0, // the progress indicator and the number of finished pages
101
- finished; // is the pagination finished?
85
+ finished, // is the pagination finished?
86
+ SP = new URLSearchParams(location.search);
102
87
 
103
- // Diagnosis: pages that overflow, elements with scrollbars, and unbreakable elements that
104
- // stick out of the page (listed in a panel, see addTools())
88
+ // Diagnosis (listed in a panel, see addTools()): pages that overflow, elements with
89
+ // scrollbars, and unbreakable elements that stick out of the page
105
90
  const hit = 'pagesjs-hit', px = n => Math.round(n);
91
+ function unhit() { $('.' + hit)?.classList.remove(hit); }
106
92
  function problems() {
107
93
  const out = [], sc = /auto|scroll/, scrolls = [];
108
94
  boxes.forEach((b, i) => {
@@ -110,7 +96,8 @@
110
96
  has(b, 'page-multiple') && out.push([b, `${p} overflows`]);
111
97
  $$('*', body).forEach(el => {
112
98
  const cs = style(el), name = el.tagName.toLowerCase() + (el.className && '.' + el.classList[0]);
113
- if (sc.test(cs.overflowX) || sc.test(cs.overflowY)) { // (read sizes only of these: each is a layout read)
99
+ // (read sizes only of scrolling elements: each read is a layout)
100
+ if (sc.test(cs.overflowX) || sc.test(cs.overflowY)) {
114
101
  const {clientWidth: cw, clientHeight: ch, scrollWidth: sw, scrollHeight: sh} = el;
115
102
  if (sc.test(cs.overflowX) && sw > cw + 1 || sc.test(cs.overflowY) && sh > ch + 1)
116
103
  return scrolls.push(el), out.push([el, `${p} ${name} scrolls: ${sw}x${sh} in ${cw}x${ch}`]);
@@ -130,13 +117,12 @@
130
117
  el && !$('.pagesjs-body', el) && el.insertAdjacentHTML('afterbegin', tpl.innerHTML);
131
118
  box = el || tpl.cloneNode(true); box_body = box.children[1]; box_ctx = null;
132
119
  portrait && ([H, B] = portrait);
133
- boxes.includes(box) || boxes.push(box); // store new pages in boxes
120
+ boxes.includes(box) || boxes.push(box);
134
121
  return box;
135
122
  }
136
- // The margin at the end of the content of a page is truncated at the end of the
137
- // page (like in CSS fragmentation), so it should not count when the content is
138
- // tested if it fits the page. It is the margin of the last element and its last
139
- // descendants, until one with padding/border at the bottom.
123
+ // The margin at the end of the content of a page is truncated at the page end (as in
124
+ // CSS fragmentation), so it does not count in the fit test: the margin of the last
125
+ // element and its last descendants, up to one with padding/border at the bottom.
140
126
  function trailingMargin(body = box_body) {
141
127
  let m = 0;
142
128
  for (let e = lastEl(body); e; e = lastEl(e)) {
@@ -146,17 +132,16 @@
146
132
  }
147
133
  return m;
148
134
  }
149
- // the height of the page without the margin at the end of its content
150
- function pageHeight() { syncNotes(); return crowded() ? Infinity : rect(box).height - trailingMargin(); }
151
- // does the page overflow?
135
+ // How far (px) the page, without the margin at the end of its content, goes beyond what
136
+ // fits: it fits if its height rounds to H or less (< H + .5).
137
+ function excess() { syncNotes(); return (crowded() ? Infinity : rect(box).height - trailingMargin()) - H - .5; }
152
138
  function overflows() { syncNotes(); return (used = box.scrollHeight - trailingMargin()) > H || crowded(); }
153
- // Nothing fits on the page of a float that takes it: is the page taken, and is there
154
- // anything after the float?
139
+ // Does a float take the page, with something after it? Then nothing else fits.
155
140
  function taken() { return !!whole && box_body.contains(whole); }
156
141
  function crowded() { return taken() && hasAround(whole, 'next'); }
157
- // The notes are not measured inline (where they are floats next to their references),
158
- // but in a block after the page body, as in the end: put the notes of the references
159
- // that are on the page there (and take the others off).
142
+ // Notes are measured in a block after the page body, as in the end, not inline (where
143
+ // they are floats next to their references): put the notes of the references on the
144
+ // page there, and take off the others.
160
145
  function syncNotes(b = box) {
161
146
  const body = b.children[1], ms = [...$$('.pagesjs-note', body)], seen = new Set();
162
147
  // a note cited more than once on the page is shown once (with its first reference)
@@ -172,16 +157,15 @@
172
157
  c.className = 'footnotes';
173
158
  if (items.some((e, i) => c.children[i] !== e) || nChild(c) !== items.length) c.replaceChildren(...items);
174
159
  }
175
- // start the next page and finish current page
176
160
  function nextPage(el, callback) {
177
161
  const cur = box; cur.after(newPage(el)); callback && callback(); putFloats(); finish(cur);
178
162
  }
179
- // compute page numbers and temporarily remove the box
163
+ // compute page numbers and remove the box from the DOM
180
164
  function finish(box) {
181
165
  syncNotes(box);
182
166
  const h = box.scrollHeight, wide = has(box, 'page-wide'), Hb = (wide ? landscape : portrait)[0];
183
- // tolerate a few pixels (and the margin of the last element) hanging over the page bottom
184
- // (a landscape page is not continued; what sticks out of it is reported, see problems())
167
+ // tolerate a few pixels (and a last margin) hanging over the bottom; a landscape page is
168
+ // not continued (what sticks out of it is reported, see problems())
185
169
  if (!wide && h - trailingMargin(box.children[1]) > Hb && !box.dataset.pagesOffset) {
186
170
  const n = calcPages(box, h, Hb);
187
171
  if (n > 1) box.dataset.pagesOffset = n, guessed.add(box);
@@ -189,11 +173,10 @@
189
173
  box.remove();
190
174
  progress && (progress.textContent = `Paginating: ${++n_done} pages done`);
191
175
  }
192
- // The height of a page in fill mode is its natural height, which includes spaces that
193
- // are not needed in the end (e.g., the margins of the last element), so a page that is a
194
- // few pixels too tall may be fine with its fixed height. Check the pages in the end:
195
- // if the content doesn't reach the notes/footer after the body and nothing hangs over
196
- // the paper, the estimated number of pages is wrong.
176
+ // A page in fill mode has its natural height, which includes space not needed in the end
177
+ // (e.g., the last margin), so a page a few pixels too tall may be fine at its fixed height.
178
+ // If the content does not reach the notes/footer and nothing hangs over the paper, the
179
+ // estimated number of pages is wrong.
197
180
  function checkOffsets() {
198
181
  boxes.forEach(box => {
199
182
  if (!guessed.has(box)) return;
@@ -203,15 +186,13 @@
203
186
  box.scrollHeight <= box.clientHeight + 1) delete box.dataset.pagesOffset;
204
187
  });
205
188
  }
206
- // calculate how many new pages we need for overflowed content (this is just
207
- // an estimate; if not accurate, use <div class="pagesjs-page" data-pages-offset="N">
208
- // to provide a number manually)
189
+ // number of pages for the overflow (an estimate; set data-pages-offset="N" to override)
209
190
  function calcPages(box, h, H) {
210
191
  let n = +box.dataset.pagesOffset;
211
192
  if (n) return n;
212
193
  n = Math.ceil(h/H);
213
194
  if (n <= 1) return n;
214
- // consider top/bottom page margin and table headers (which may be repeated on each page)
195
+ // consider the top/bottom margins and table headers (repeated on each page)
215
196
  const m = tb.concat([...$$('thead', box)].map(el => +el.offsetHeight)).reduce((m1, m2) => m1 + m2);
216
197
  if (!m) return n;
217
198
  function nPages() { return Math.ceil((h + (n - 1) * m)/H); }
@@ -228,14 +209,14 @@
228
209
  for (; el && el !== d.body; el = el.parentNode) a.unshift(el);
229
210
  return a;
230
211
  }
231
- // The container for the content on the current page. It is a chain of empty
232
- // clones of the content root and its ancestors (i.e., the original context), so
233
- // CSS selectors that depend on them (e.g., `main h2`) still apply on pages.
234
212
  // an empty clone of el that keeps its context for CSS selectors but not its box
235
213
  function wrapper(el) {
236
- const c = el.cloneNode(); addCls(c, 'pagesjs-wrap'); rmCls(c, fr_cls, fr_1, fr_2);
214
+ const c = el.cloneNode(); addCls(c, 'pagesjs-wrap'); unfrag(c);
237
215
  return c;
238
216
  }
217
+ // The container for content on the current page: clones of the content root and its
218
+ // ancestors, so selectors like `main h2` still apply on pages.
219
+ function setRoot(el) { wrap = el ? ancestors(el) : []; box_ctx = null; }
239
220
  function ctx() {
240
221
  if (!wrap.length) return box_body;
241
222
  if (!box_ctx || !box_body.contains(box_ctx)) {
@@ -245,7 +226,7 @@
245
226
  }
246
227
  function removeBlank(el) {
247
228
  if (!el || el.tagName === 'BODY') return false;
248
- // for <p>, don't treat it as empty unless its HTML is empty
229
+ // (a <p> is empty only if its HTML is)
249
230
  const v = !(el.tagName === 'P' ? el.innerHTML : el.innerText).trim();
250
231
  v && el.remove();
251
232
  return v;
@@ -254,38 +235,34 @@
254
235
  // --- Putting elements on pages -------------------------------------
255
236
 
256
237
  function* fill(el, more = true) {
257
- // if the element is already a page, just use it as the box
238
+ // a page element is used as the box
258
239
  if (has(el, 'pagesjs-page')) {
259
240
  nextPage(el, () => nChild(el) > 3 && (
260
- // if current element is not empty, fill its content into the box
241
+ // (its content goes into the box; TODO: fragment it if it's too long)
261
242
  box_body.append(...kids(el).slice(3)),
262
- // TODO: should we fragment this page if it's too long?
263
- nextPage() // create a new empty page
243
+ nextPage()
264
244
  ));
265
245
  } else {
266
- // in a book, a chapter (a container of <h1>) starts on a new page
267
246
  if (book && box.innerText !== '' && $('h1', el)) flush(), nextPage();
268
247
  if (el.innerText.trim() && (taken() || (syncNotes(), H - box.scrollHeight < H_min))) nextPage();
269
248
  yield* place(el, more);
270
249
  }
271
250
  }
272
251
 
273
- // append el to the page, and if it overflows, put as much of it as possible on
274
- // the page and the rest on the next page(s)
252
+ // append el to the page; if it overflows, put as much as possible on the page and
253
+ // the rest on the next page(s)
275
254
  function* place(el, more) {
276
255
  for (;;) {
277
- const c = ctx();
256
+ const c = ctx(), big = isBigBlock(el);
278
257
  endFrag(el);
279
- if (isBigBlock(el)) {
280
- // don't attach a big element to the page, since it takes time to style
281
- // and lay out all its content just to find out that it does not fit
282
- el = split(el, c, 'block', more);
283
- } else {
258
+ // a big block is not attached to the page: styling and laying out all its content
259
+ // just to find out that it does not fit takes time
260
+ if (!big) {
284
261
  c.append(el);
285
262
  if (isFloat(el) && !stays(el, c)) return;
286
263
  if (!overflows()) return;
287
- el = split(el, c, undefined, more);
288
264
  }
265
+ el = split(el, c, big ? 'block' : undefined, more);
289
266
  if (!el) return;
290
267
  nextPage();
291
268
  yield; // (a chance to paint the progress)
@@ -293,11 +270,11 @@
293
270
  }
294
271
  }
295
272
 
296
- // Put as much of el (which has just overflowed the page in container) as
297
- // possible into container, and return the rest (detached) if any. Unless el is
298
- // the first thing on the page, it will be left out entirely if it can't be broken.
273
+ // Put as much of el (which just overflowed container) as possible into container, and
274
+ // return the rest (detached), if any. Unless el is first on the page, it is left out
275
+ // entirely if it can't be broken.
299
276
  function split(el, container, kind, more) {
300
- // (for a block, prev is determined after it is cut, to avoid laying it out)
277
+ // (a block's prev is determined after it is cut, to avoid laying it out)
301
278
  const k = kind || kindOf(el), prev = k === 'block' ? undefined : hasPrev(el),
302
279
  first = !has(el, fr_cls), r = k && splitters[k](el, container, prev, first, more);
303
280
  if (!r) return prev && (el.remove(), isFloat(el) ? defer(el, container) : el);
@@ -306,55 +283,49 @@
306
283
  if (rest) {
307
284
  addCls(rest, fr_cls); rmCls(rest, fr_1, fr_2);
308
285
  } else if (has(head, fr_1)) {
309
- rmCls(head, fr_cls, fr_1, fr_2); // it's not really split
286
+ unfrag(head); // (not really split)
310
287
  } else {
311
288
  addCls(head, fr_2); // the last piece
312
289
  }
313
290
  return rest;
314
291
  }
292
+ function unfrag(el) { rmCls(el, fr_cls, fr_1, fr_2); }
315
293
 
316
- // Floats are captioned figures and elements with the class "pagesjs-float". They are never
317
- // broken: one that does not fit where it is waits for the next page, and the content
318
- // after it fills the page, as in LaTeX. They keep their order (a float waits if an
319
- // earlier one does), and wait at most until the end of the chapter (book) or the root.
294
+ // Floats: captioned figures and .pagesjs-float elements. They keep their order (one waits
295
+ // if an earlier one does), and wait at most until the end of the chapter (book) or the root.
320
296
  function isFloat(el) {
321
297
  return el.matches('.pagesjs-float, .pagesjs-wide') || el.matches('figure, .figure') && !!$('figcaption, .caption', el);
322
298
  }
323
- // does a float take a whole page?
324
299
  function isTall(f) { return has(f, 'pagesjs-wide') || rect(f).height > B * floatPage / 100; }
325
- // let a float take the page: overflows() keeps everything else off the page, and
326
- // the class makes the body center the float vertically (see pages.css). A wide one
327
- // gets a landscape page (the sizes of the page are those of the paper turned).
300
+ // Let a float take the page: overflows() keeps everything else off it, and the class
301
+ // centers the float (pages.css). A wide float gets a landscape page.
328
302
  function takePage(f) {
329
303
  whole = f; addCls(box, 'page-float');
330
304
  has(f, 'pagesjs-wide') && (addCls(box, 'page-wide'), [H, B] = landscape);
331
305
  }
332
- // Does a float (attached to container) stay where it is? Not if floats wait before it,
333
- // or if it takes a whole page and there is content before it: it goes to a page of its own.
306
+ // Does a float (attached to container) stay? Not if floats wait before it, or if it takes
307
+ // a page and there is content before it: then it goes to a page of its own.
334
308
  function stays(f, container) {
335
309
  const tall = isTall(f);
336
310
  if (floats.length || tall && hasPrev(f)) return defer(f, container, tall), false;
337
311
  tall && takePage(f);
338
312
  return true;
339
313
  }
340
- // does the next page belong to a float that takes a page? (then the rest of what is
341
- // broken on this page is not on the next page, and should not be a lone line)
342
- function tallWaiting() { return floats[0]?.[2]; }
343
- // (a float keeps the wrappers of the pieces of the elements that it was in, e.g., a
344
- // chapter, so the CSS selectors that depend on them still work on the next page)
314
+ // (the waiting float keeps the wrappers of the elements it was in, e.g., a chapter, so
315
+ // selectors that depend on them still work on the next page)
345
316
  function defer(el, container, tall) {
346
317
  const chain = [];
347
318
  for (let p = container, top = ctx(); p && p !== top; p = p.parentNode) chain.unshift(wrapper(p));
348
319
  el.remove(); floats.push([el, chain, tall]);
349
320
  }
350
- // put the waiting floats at the top of the new page, in order, as many as fit (the
351
- // first one stays even if it is too big, since it can't wait any longer)
321
+ // Put the waiting floats at the top of the new page, in order, as many as fit. The first
322
+ // stays even if too big, since it can't wait any longer.
352
323
  function putFloats() {
353
324
  while (floats.length) {
354
325
  const [f, chain] = floats[0], out = chain[0] || f;
355
326
  chain.reduce((p, c) => p.appendChild(c), ctx()).append(f);
356
327
  // the first float on the page stays (centered if it takes the page); the others
357
- // only if they are short and fit
328
+ // only if short and fitting
358
329
  if (hasPrev(out)) {
359
330
  if (isTall(f) || overflows()) return out.remove();
360
331
  } else isTall(f) && takePage(f);
@@ -366,13 +337,11 @@
366
337
  while (floats.length) nextPage();
367
338
  }
368
339
 
369
- // is an element a block that is too big to be put on a page as a whole?
370
340
  function isBigBlock(el) {
371
341
  return !isFloat(el) && !['TABLE', 'PRE'].includes(el.tagName) && el.getElementsByTagName('*').length > 300;
372
342
  }
373
343
  function blank(el) { return !firstEl(el) && !el.textContent.trim(); }
374
- // is there anything before ('previous') or after ('next') el on the page (if there is
375
- // something before it, el may go to the next page)?
344
+ // is there anything before ('previous') or after ('next') el on the page?
376
345
  function hasAround(el, side) {
377
346
  const k = side + 'ElementSibling';
378
347
  for (; el && el !== box_body; el = el.parentNode)
@@ -384,19 +353,18 @@
384
353
  function inFlow(cs) {
385
354
  return cs.float === 'none' && !['absolute', 'fixed'].includes(cs.position);
386
355
  }
387
- // text, inline elements, and out-of-flow elements go with the text around them
356
+ // text, inline and out-of-flow nodes go with the text around them
388
357
  function isInline(n) {
389
358
  if (n.nodeType !== 1) return true;
390
359
  const cs = style(n), v = cs.display;
391
360
  return v.startsWith('inline') || v === 'none' || v === 'contents' || !inFlow(cs);
392
361
  }
393
- // is an element a part of the text (inline, and not a float, etc.)?
394
362
  function inTextFlow(el) {
395
363
  const cs = style(el);
396
364
  return (cs.display.startsWith('inline') || cs.display === 'contents') && inFlow(cs);
397
365
  }
398
- // lines of <pre><code>; tags open at the end of a line (e.g., a multi-line
399
- // comment) are closed there and reopened on the next line, so each line is balanced
366
+ // lines of <pre><code>; a tag open at a line end (e.g., a multi-line comment) is closed
367
+ // there and reopened on the next line, so each line is balanced
400
368
  function codeLines(pre) {
401
369
  const open = [];
402
370
  return firstEl(pre).innerHTML.replace(/\n$/, '').split('\n').map(line => {
@@ -407,8 +375,8 @@
407
375
  return start + line + open.map(t => `</${t[1]}>`).reverse().join('');
408
376
  });
409
377
  }
410
- // how can the element be broken: by 'block' (its child blocks), 'inline' (text
411
- // lines), 'table' (rows), 'code' (lines), or not at all (undefined)?
378
+ // how the element can be broken: 'block' (child blocks), 'inline' (text lines), 'table'
379
+ // (rows), 'code' (lines), or not at all (undefined)?
412
380
  function kindOf(el) {
413
381
  const cs = style(el), t = el.tagName;
414
382
  if (/avoid/.test(cs.breakInside) || el.matches(atomic)) return;
@@ -416,7 +384,7 @@
416
384
  if (!['block', 'list-item', 'flow-root'].includes(cs.display) || !inFlow(cs)) return;
417
385
  if (t === 'PRE') {
418
386
  if (firstEl(el)?.tagName === 'CODE' && codeLines(el).length > 1) return 'code';
419
- // wrapped long lines: move to the next page if it fits there, otherwise break by lines
387
+ // wrapped long lines: move to the next page if it fits there, else break by lines
420
388
  if (el.offsetHeight <= B) return;
421
389
  }
422
390
  return kids(el).some(c => !isInline(c)) ? 'block' : 'inline';
@@ -424,37 +392,36 @@
424
392
  function mark(el, first) {
425
393
  addCls(el, fr_cls); rmCls(el, fr_2); first && addCls(el, fr_1);
426
394
  }
427
- // pieces of a fragmented element that are put on a page as a whole are the last
428
- // pieces; mark them (and their fragmented descendants) before measuring, since
429
- // the size of the last piece is different (see pages.css); if it turns out to be
430
- // too big and is split, the mark is removed
395
+ // The pieces that are put on a page as a whole are the last pieces. Mark them (and their
396
+ // fragmented descendants) before measuring, since the last piece is styled differently
397
+ // (pages.css). If it is split after all, the mark is removed.
431
398
  function endFrag(el) {
432
399
  if (el.nodeType === 1) [el, ...$$('.' + fr_cls, el)].forEach(e => has(e, fr_cls) && addCls(e, fr_2));
433
400
  }
434
- // shallow clone el (wrapper only) as the first piece of el in container
401
+ // shallow clone of el (as its first piece) in container
435
402
  function cut(el, container, first) {
436
403
  const head = el.cloneNode();
437
404
  el.remove(); container.append(head); mark(head, first);
438
405
  return head;
439
406
  }
440
- // wrap each run of inline nodes in a block (like an anonymous block box in CSS)
441
- // so mixed content (e.g., <li>text<ul>...</ul></li>) can be broken as paragraphs
407
+ // wrap each run of inline nodes in a block (like an anonymous block box in CSS), so mixed
408
+ // content (e.g., <li>text<ul>...</ul></li>) can be broken like paragraphs
442
409
  function wrapRuns(el) {
443
410
  // (a run is made of inline nodes already; wrapping it again would nest runs endlessly)
444
411
  if (wrapped.has(el) || has(el, 'pagesjs-run')) return;
445
412
  wrapped.add(el);
446
- // computed styles are available only in the DOM (but not necessarily on a page)
413
+ // computed styles are only available in the DOM
447
414
  el.isConnected || hold.append(el);
448
415
  let run = [];
449
- function flush() {
416
+ function endRun() {
450
417
  if (run.some(n => n.nodeType === 1 || n.nodeType === 3 && n.nodeValue.trim())) {
451
418
  const s = make('span', 'pagesjs-run');
452
419
  run[0].before(s); s.append(...run);
453
420
  }
454
421
  run = [];
455
422
  }
456
- for (const n of [...el.childNodes]) isInline(n) ? run.push(n) : flush();
457
- flush();
423
+ for (const n of [...el.childNodes]) isInline(n) ? run.push(n) : endRun();
424
+ endRun();
458
425
  el.parentNode === hold && el.remove();
459
426
  }
460
427
 
@@ -462,12 +429,10 @@
462
429
 
463
430
  // --- Breaking elements ---------------------------------------------
464
431
 
465
- // Measuring the page after each child is slow (a forced layout), so put several children
466
- // on it at once when they surely fit: the nodes (in order) that end a line above the page
467
- // bottom, going by their distances on the probe page from the last child on the page. If
468
- // they turn out not to fit, they are taken back, so the estimate affects the speed but not
469
- // the result. The children of the content root need the room that fill() asks for (H_min,
470
- // and as much again for the margin after the previous child).
432
+ // Measuring after each child is slow (a forced layout), so put several children on the page
433
+ // at once when they surely fit, by their probe positions from the last child on the page.
434
+ // If they don't fit, they are taken back, so the estimate affects speed, not the result.
435
+ // Children of the content root need the room fill() asks for (H_min, plus the margin).
471
436
  function fitting(head, nodes, root) {
472
437
  const prev = lastEl(head), y0 = prev && !has(prev, fr_cls) ? probeY.get(prev) : undefined, run = [];
473
438
  if (y0 === undefined || !used) return run;
@@ -485,8 +450,8 @@
485
450
  return run.slice(0, n);
486
451
  }
487
452
  function* siblings(n) { for (; n; n = n.nextSibling) yield n; }
488
- // move children to a clone of el one by one until the page is full, and split
489
- // the child that overflows recursively, so elements can be broken at any depth
453
+ // move children to a clone of el one by one until the page is full; the child that
454
+ // overflows is split recursively, so elements can be broken at any depth
490
455
  function splitBlock(el, container, prev, first, more) {
491
456
  wrapRuns(el);
492
457
  const head = cut(el, container, first);
@@ -516,34 +481,33 @@
516
481
  return [head, blank(el) ? null : el];
517
482
  }
518
483
 
519
- // a legend or a caption (which is too tall for moveShortHead() when it's in a framed
520
- // block or above a table) should not be the last child of a piece that is continued,
521
- // so move it (and those before it) to the rest (el)
484
+ // A legend or caption should not end a piece that is continued (it is too tall for
485
+ // moveShortHead() in a framed block or above a table): move it, and those before it, to el.
522
486
  function moveTrailingHeadings(head, el, prev) {
523
487
  for (let h; (h = lastEl(head))?.matches('legend, .caption') && (nChild(head) > 1 || prev);)
524
488
  el.prepend(h);
525
489
  }
526
- // if only about one line (e.g., a legend or the first list item) is left on the
527
- // page, and no child was split, move it to the next page with the rest (el)
490
+ // If about one line (e.g., a legend or the first list item) is left and no child was split,
491
+ // move it to the next page with the rest
528
492
  function moveShortHead(head, el) {
529
493
  if (!blank(el) && rect(head).height < 1.5 * H_line) {
530
494
  rejoin(lastEl(head), firstEl(el));
531
495
  el.prepend(...head.childNodes);
532
496
  }
533
497
  }
534
- // put back the piece a (at the end of the head) into its rest b (at the start of el),
535
- // so they are one element again
498
+ // put the piece a (at the end of head) back into its rest b (at the start of el), so they
499
+ // are one element again
536
500
  function rejoin(a, b) {
537
501
  if (!a || !b || !has(a, fr_cls) || !has(b, fr_cls) || a.tagName !== b.tagName) return;
538
502
  rejoin(lastEl(a), firstEl(b));
539
503
  b.prepend(...a.childNodes);
540
- // (b is not marked as the last piece yet; if a was the first piece, they are the original element)
504
+ // (b is not marked as the last piece; if a was the first piece, they are the original element)
541
505
  rmCls(b, ...has(a, fr_1) ? [fr_cls, fr_1, fr_2] : [fr_1]);
542
506
  a.remove();
543
507
  }
544
- // If all children fit, head is the last piece, which has bottom margin/border
545
- // that were hidden when it was measured as a non-last piece; if it is too
546
- // big now, break the last child (or push it out entirely if it can't be broken).
508
+ // If all children fit, head is the last piece, whose bottom margin/border was hidden when it
509
+ // was measured as a non-last piece. If it is too big now, break its last child (or push
510
+ // that out entirely if it can't be broken).
547
511
  function fitLastPiece(head, el, prev) {
548
512
  addCls(head, fr_2);
549
513
  while (overflows() && lastEl(head) && (nChild(head) > 1 || prev)) {
@@ -554,7 +518,7 @@
554
518
  }
555
519
  blank(el) || rmCls(head, fr_2);
556
520
  }
557
- // update the start number of the rest of <ol> (an item split in half counts once)
521
+ // update the start number of the rest of <ol> (a split item counts once)
558
522
  function fixOlStart(head, el) {
559
523
  el.start += nChild(head) - (has(firstEl(el), fr_cls) ? 1 : 0);
560
524
  }
@@ -569,49 +533,47 @@
569
533
  loc.i < 0 ? r.setStartBefore(loc.node) : r.setStart(loc.node, loc.i);
570
534
  r.setEnd(el, el.childNodes.length);
571
535
  rest.prepend(r.extractContents());
572
- const last = el.lastChild; // strip trailing empty tags left by range extraction
536
+ const last = el.lastChild; // strip trailing empty tags left by the extraction
573
537
  last?.innerHTML === '' && last.remove();
574
538
  }
575
539
  mark(el, first);
576
- // remove lines from the end of paragraph (but keep the first line if el is
577
- // the first thing on the page)
540
+ // remove lines from the end (keep the first line if el is first on the page)
578
541
  while (k > (prev ? 0 : 1)) {
579
542
  cutLine();
580
543
  if (k > 0 && !overflows()) break;
581
544
  }
582
- // avoid a widow only when it is the very last line of the content, i.e.,
583
- // alone on a page (an orphan, or a widow followed by more content, is fine); or when
584
- // it would come after a page of a float (the paragraph moves entirely if it has 2 lines)
585
- if (n - k === 1 && (k > 1 && !more || (k > 1 || prev) && tallWaiting())) cutLine();
545
+ // avoid a widow only when it is the very last line of the content (alone on a page), or
546
+ // when a tall float waits (then the paragraph moves entirely if it has 2 lines)
547
+ if (n - k === 1 && (k > 1 && !more || (k > 1 || prev) && floats[0]?.[2])) cutLine();
586
548
  return [el, rest];
587
549
  }
588
550
 
589
- // find the break position of each line (exclude block elements like footnotes)
551
+ // find the break position of each line (blocks like footnotes are excluded)
590
552
  function lineStarts(el) {
591
553
  const r = range(), ends = [{node: el, i: 0}];
592
554
  const walker = d.createTreeWalker(el, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
593
555
  let node, prev;
594
- // if the previous rect is at top-right of current rect, assume a line ends
595
- // before the current one (TODO: how about RTL languages?)
596
- function newLine(rect) {
597
- return prev && prev.bottom <= rect.top && prev.right > rect.left;
556
+ // if the previous rect is at the top-right of the current one, a line ends before it
557
+ // (TODO: how about RTL languages?)
558
+ function newLine(rc) {
559
+ return prev && prev.bottom <= rc.top && prev.right > rc.left;
598
560
  }
599
561
  while (node = walker.nextNode()) {
600
562
  const t = node.tagName;
601
563
  if (t) {
602
564
  if (t === 'MJX-CONTAINER' || (t === 'SPAN' && $('.katex', node)) || !inTextFlow(node)) {
603
- node = walker.nextSibling(); // skip blocks and floats (footnotes) and math
565
+ node = walker.nextSibling(); // skip blocks, floats (footnotes), and math
604
566
  if (!node) break;
605
567
  }
606
- if (node.firstChild) continue; // for element nodes, traverse to bottom
568
+ if (node.firstChild) continue; // element nodes: traverse to the bottom
607
569
  }
608
570
  if (node.tagName) {
609
571
  const rc = rect(node);
610
572
  newLine(rc) && ends.push({node, i: -1});
611
573
  prev = rc;
612
574
  } else if (node.textContent.trim()) {
613
- // a text node has one rect per line, and a new line starts at the first
614
- // character that makes the range of the text have one more rect
575
+ // a text node has one rect per line; a new line starts at the first character
576
+ // that adds one rect to the range
615
577
  r.selectNodeContents(node);
616
578
  const rects = r.getClientRects();
617
579
  if (!rects.length) continue;
@@ -622,19 +584,36 @@
622
584
  }
623
585
  return ends;
624
586
  }
625
- // the offset of the first character on the k-th line of a text node (via bisection)
626
- function lineOffset(node, k, r) {
627
- let lo = 0, hi = node.length;
587
+ // the first i in [0, n) for which the monotone test is true (n if none)
588
+ function bisect(n, test) {
589
+ let lo = 0, hi = n;
628
590
  while (lo < hi) {
629
591
  const mid = (lo + hi) >> 1;
630
- r.setStart(node, 0); r.setEnd(node, mid);
631
- r.getClientRects().length > k ? hi = mid : lo = mid + 1;
592
+ test(mid) ? hi = mid : lo = mid + 1;
632
593
  }
633
- return lo - 1; // (the range ends after the first character of the line)
594
+ return lo;
595
+ }
596
+ // the offset of the first character on the k-th line of a text node
597
+ function lineOffset(node, k, r) {
598
+ // (the range ends after the first character of the line)
599
+ return bisect(node.length, mid => (r.setStart(node, 0), r.setEnd(node, mid), r.getClientRects().length > k)) - 1;
600
+ }
601
+ // How many of n pieces (rows or lines) fit the page? All of them are on it, and laid out
602
+ // once; the pieces whose bottoms are below (the bottom of the last one - the excess) do not
603
+ // fit. show(i) puts only the first i pieces on the page, which is checked and fixed in the
604
+ // end (a break may not be at the bottom of a piece). skip(i) may adjust the estimate.
605
+ function fitCount(n, bottom, min, show, skip = i => i) {
606
+ const over = excess();
607
+ if (over < 0) return n;
608
+ const limit = bottom(n - 1) - over;
609
+ let i = skip(bisect(n, j => bottom(j) > limit));
610
+ show(Math.max(i, min));
611
+ while (i > min && excess() > 0) show(--i);
612
+ return Math.max(i, min);
634
613
  }
635
- // A copy of a repeated table header/footer. The notes in it appear once, on the first
636
- // page: the first copy takes the markers of the original, so later copies have none.
637
- // undo gets the functions that give the markers back (if the copy is discarded).
614
+ // A copy of a repeated table header/footer. Its notes appear once, on the first page: the
615
+ // first copy takes the markers of the original, so later copies have none. undo puts the
616
+ // markers back (if the copy is discarded).
638
617
  function cloneHold(el, undo) {
639
618
  const c = el.cloneNode(true), ms = $$('.pagesjs-note', c);
640
619
  $$('.pagesjs-note', el).forEach((m, i) => {
@@ -648,28 +627,15 @@
648
627
  function splitTable(el, container, prev, first) {
649
628
  const head = cut(el, container, first), tb = el.tBodies[0], tb2 = tb.cloneNode(),
650
629
  undo = [], rows = [...tb.rows], n = rows.length, min = prev ? 0 : 1;
651
- // the caption (which is not broken) goes with the first rows, unless it is below the table
630
+ // the caption (not broken) goes with the first rows, unless it is below the table
652
631
  const cap = el.caption && style(el.caption).captionSide !== 'bottom' ? el.caption : null;
653
632
  function clear() { cap && el.prepend(cap); head.innerHTML = ''; undo.reverse().forEach(f => f()); }
654
633
  cap && head.append(cap);
655
- // copy table header and footer (the header goes first, as in the original)
634
+ // copy the table header and footer (the header goes first, as in the original)
656
635
  [el.tHead, tb2, el.tFoot].forEach(t => t && head.append(t === tb2 ? t : cloneHold(t, undo)));
657
- // Put all rows in the page and lay them out once. The rows whose bottoms are
658
- // below (the bottom of the last row - the overflow) do not fit; put them back.
659
636
  tb2.append(...rows);
660
- const over = pageHeight() - H - .5; // (see fitLines())
661
- if (over >= 0) {
662
- const limit = rect(rows[n - 1]).bottom - over;
663
- let lo = 0, hi = n; // the first row that is below the limit (by bisection)
664
- while (lo < hi) {
665
- const mid = (lo + hi) >> 1;
666
- rect(rows[mid]).bottom <= limit ? lo = mid + 1 : hi = mid;
667
- }
668
- let k = Math.max(lo, min);
669
- tb.prepend(...rows.slice(k));
670
- while (k > min && pageHeight() > H + .5) tb.prepend(rows[--k]); // make sure they fit
671
- }
672
- // clear the clone if current page can't fit even one row
637
+ fitCount(n, j => rect(rows[j]).bottom, min, k => tb.prepend(...rows.slice(k)));
638
+ // clear the clone if the current page can't fit even one row
673
639
  tb2.rows.length || clear();
674
640
  // avoid a single row on either page
675
641
  const m = tb2.rows.length;
@@ -679,11 +645,11 @@
679
645
  }
680
646
  return [head, tb.rows.length ? el : null];
681
647
  }
682
- // split lines in <code> and move as many lines into the clone as possible
648
+ // split lines in <code>, moving as many lines into the clone as possible
683
649
  function splitCode(el, container, prev, first) {
684
650
  const code = firstEl(el), lines = codeLines(el);
685
- // other children go to the first piece, except those after <code> in the normal
686
- // flow (e.g., a link to the output), which go to the last piece
651
+ // other children go to the first piece, except those after <code> in the normal flow
652
+ // (e.g., a link to the output), which go to the last piece
687
653
  const ch = kids(el), tail = ch.filter((c, j) => j > ch.indexOf(code) && inFlow(style(c)));
688
654
  const head = cut(el, container, first), code2 = code.cloneNode();
689
655
  head.append(code2, ...ch.filter(c => c !== code && !tail.includes(c)));
@@ -691,59 +657,48 @@
691
657
  // avoid a single line on either page
692
658
  if (i > 1 && lines.length - i === 1) i--;
693
659
  if (i === 1 && prev) i = 0;
694
- // i == 0 means not enough space to split code on current page
660
+ // i == 0: not enough space on the current page
695
661
  if (i) code2.innerHTML = lines.slice(0, i).join('\n'); else head.innerHTML = '';
696
662
  code.innerHTML = lines.slice(i).join('\n');
697
663
  if (code.innerHTML.trim()) return [head, el];
698
664
  i && head.append(...tail);
699
665
  return [head, null];
700
666
  }
701
- // Figure out how many lines can fit the box. Instead of guessing and testing
702
- // different numbers of lines, put all lines in <code> and lay them out once, and
703
- // read the positions of the line breaks, which tells how many lines are below
704
- // the bottom of the page. (Lines are balanced, so their line breaks are in the
705
- // text nodes that are children of <code>.)
667
+ // How many lines fit the box? The positions of the line breaks tell (lines are balanced,
668
+ // so the breaks are in the text nodes that are children of <code>).
706
669
  function fitLines(code, lines, prev) {
707
- const n = lines.length, min = prev ? 0 : 1;
708
- code.innerHTML = lines.join('\n');
709
- // (the page fits if its height is rounded to H or less, i.e., it is < H + .5)
710
- const over = pageHeight() - H - .5;
711
- if (over < 0) return n;
712
- const r = range(), bottoms = []; // the bottom of each line
713
- code.childNodes.forEach(node => {
714
- if (node.nodeType !== 3) return;
715
- for (let i = node.data.indexOf('\n'); i >= 0; i = node.data.indexOf('\n', i + 1)) {
716
- r.setStart(node, i); r.setEnd(node, i + 1);
717
- bottoms.push(rect(r).bottom);
718
- }
719
- });
720
- // the bottom of the last line (which has no line break), and the space after it
721
- r.selectNodeContents(code);
722
- const rects = r.getClientRects(), last = rects[rects.length - 1].bottom;
723
- bottoms.push(last);
724
- // the lines whose bottoms are not below (the bottom of the last line - over)
725
- let i = 0;
726
- while (i < n && bottoms[i] <= last - over) i++;
727
- // blank lines at the end don't take space, so don't leave them to the next page
728
- while (i && i < n && !lines[i].trim()) i++;
729
- code.innerHTML = lines.slice(0, Math.max(i, min)).join('\n');
730
- // make sure that the lines fit (e.g., when the line break is not at the bottom
731
- // of a line)
732
- while (i > min && pageHeight() > H + .5) {
733
- code.innerHTML = lines.slice(0, --i).join('\n');
670
+ const show = i => code.innerHTML = lines.slice(0, i).join('\n');
671
+ show(lines.length);
672
+ return fitCount(lines.length, j => bottoms()[j], prev ? 0 : 1, show,
673
+ // blank lines at the end take no space, so don't leave them to the next page
674
+ i => { while (i && i < lines.length && !lines[i].trim()) i++; return i; });
675
+ function bottoms() { // the bottom of each line (cached)
676
+ if (bottoms.v) return bottoms.v;
677
+ const r = range(), v = bottoms.v = [];
678
+ code.childNodes.forEach(node => {
679
+ if (node.nodeType !== 3) return;
680
+ for (let i = node.data.indexOf('\n'); i >= 0; i = node.data.indexOf('\n', i + 1)) {
681
+ r.setStart(node, i); r.setEnd(node, i + 1);
682
+ v.push(rect(r).bottom);
683
+ }
684
+ });
685
+ // the last line has no line break
686
+ r.selectNodeContents(code);
687
+ const rects = r.getClientRects();
688
+ v.push(rects[rects.length - 1].bottom);
689
+ return v;
734
690
  }
735
- return Math.max(i, min);
736
691
  }
737
692
 
738
693
  // --- Letting content settle before measuring it --------------------
739
694
 
740
- // Let content that reacts to the width of its container (e.g., diagrams that use
741
- // a ResizeObserver) settle at the page width before measuring anything: put all
742
- // content on a probe page and wait for a few frames.
695
+ // Let content that reacts to its container width (e.g., diagrams with a ResizeObserver)
696
+ // settle at the page width before measuring: put all content on a probe page, and wait
697
+ // for a few frames.
743
698
  function probe(roots, els) {
744
699
  addCls(box, 'pagesjs-settle');
745
700
  roots.forEach((el, i) => {
746
- wrap = ancestors(el); box_ctx = null; ctx().append(...els[i]);
701
+ setRoot(el); ctx().append(...els[i]);
747
702
  });
748
703
  probed = els;
749
704
  return new Promise(done => {
@@ -763,27 +718,27 @@
763
718
  if (!probed) return;
764
719
  probed.forEach(ch => ch.forEach(markY)); // (before removing anything, to lay out only once)
765
720
  probed.forEach(ch => ch.forEach(el => el.remove()));
766
- box_body.innerHTML = ''; box_ctx = null; wrap = [];
721
+ box_body.innerHTML = ''; setRoot();
767
722
  rmCls(box, 'pagesjs-settle');
768
723
  probed = null;
769
724
  }
770
725
 
771
726
  // --- Page numbers and titles ---------------------------------------
772
727
 
773
- // use data-short-title of a header if exists, and fall back to inner text
728
+ // data-short-title of a header if it exists, else its text
774
729
  function shortTitle(h) {
775
730
  return h && (h.dataset.shortTitle || h.innerText);
776
731
  }
777
732
  const ps = (book ? 'h1' : 'h2') + ':not(.pagesjs-front *)'; // page title selector
778
- // add page number, title, etc. to data-* attributes of page elements
733
+ // add page number, title, etc. to data-* attributes of the page elements
779
734
  function numberPages() {
780
735
  let page_title, i = 0;
781
736
  const u = new URL(location.href); // page URL without ?paged=1, shown on the last page
782
737
  u.searchParams.delete('paged');
783
738
  boxes.forEach(box => {
784
739
  if (book) {
785
- if ($('.pagesjs-front', box)) return; // skip book frontmatter page
786
- $(ps, box) && (page_title = ''); // empty title for first page of chapter
740
+ if ($('.pagesjs-front', box)) return; // skip the frontmatter page
741
+ $(ps, box) && (page_title = ''); // empty title for the first page of a chapter
787
742
  }
788
743
  const N = +box.dataset.pagesOffset || 1;
789
744
  if (N > 1) addCls(box, 'page-multiple');
@@ -796,12 +751,12 @@
796
751
  [box.children[0], lastEl(box)].forEach(el => {
797
752
  for (const key in info) info[key] && (el.dataset[key] = info[key]);
798
753
  });
799
- // find page title for next page
754
+ // the page title for the next page
800
755
  page_title = shortTitle([...$$(ps, box)].pop()) || page_title;
801
756
  });
802
757
  }
803
758
 
804
- // add page numbers to TOC with data-* attributes
759
+ // page numbers of the TOC entries, in data-page-number
805
760
  function numberToc() {
806
761
  $$('#TOC a[href^="#"]').forEach(a => {
807
762
  const p = d.getElementById(a.getAttribute('href').slice(1))?.closest('.pagesjs-page');
@@ -809,25 +764,49 @@
809
764
  });
810
765
  }
811
766
 
812
- // Buttons (top left) that open panels: a clone of the TOC, collapsed by default so that
813
- // readers can get it at any time; and the problems (if any) to click through.
767
+ // The button that toggles the pagination (the paged state is the query param ?paged=1)
768
+ const printer = '<svg viewBox="0 0 16 16" width="1.1em" height="1.1em" fill="none" stroke="currentColor" ' +
769
+ 'stroke-width="1.3" stroke-linejoin="round"><path d="M4.5 6V2h7v4M4.5 12h-2.5V6h12v6h-2.5"/><rect x="4.5" y="9" width="7" height="5"/></svg>';
770
+ // (a link, not a <button>, so that it is styled like the other links and icons of a page)
771
+ function toolButton(html, title, click) {
772
+ const btn = make('a');
773
+ btn.href = '#'; btn.setAttribute('role', 'button'); btn.innerHTML = html; btn.title = title;
774
+ btn.onclick = e => { e.preventDefault(); click(); };
775
+ return btn;
776
+ }
777
+ // opt out with <body data-pages-toggle="false"> (e.g., if the page has its own print button)
778
+ function noToggle() { return d.body.dataset.pagesToggle === 'false'; }
779
+ // The button of the unpaginated page. The paged view is a new history entry, so Back
780
+ // returns to the unpaginated view (see the popstate handler).
781
+ function pagedButton() {
782
+ const btn = toolButton(printer, 'Paginate for printing', () => {
783
+ paginate();
784
+ SP.set('paged', 1); history.pushState({}, '', `${location.pathname}?${SP}`);
785
+ });
786
+ btn.className = 'pagesjs-print';
787
+ return btn;
788
+ }
789
+
790
+ // Buttons (top left) of the paginated view that open panels: a clone of the TOC (collapsed,
791
+ // so readers can get it any time), and the problems, if any, to click through. Last, a
792
+ // button to print the paginated pages.
814
793
  function addTools() {
815
794
  const tools = make('div', 'pagesjs-tools'), toc = $('#TOC:not(.chapter-toc)'), bad = problems();
816
795
  const closeAll = () => {
817
796
  $$('.pagesjs-panel', tools).forEach(p => p.hidden = true);
818
- $('.' + hit)?.classList.remove(hit);
797
+ unhit();
819
798
  };
820
799
  function add(text, title, content) {
821
- const btn = make('button'), panel = make('div', 'pagesjs-panel');
822
- btn.textContent = text; btn.title = title; panel.hidden = true; panel.append(content);
823
- btn.onclick = () => { const was = panel.hidden; closeAll(); panel.hidden = !was; };
800
+ const panel = make('div', 'pagesjs-panel');
801
+ const btn = toolButton(text, title, () => { const was = panel.hidden; closeAll(); panel.hidden = !was; });
802
+ panel.hidden = true; panel.append(content);
824
803
  tools.append(btn, panel);
825
804
  return panel;
826
805
  }
827
806
  if (toc) {
828
807
  const nav = toc.cloneNode(true);
829
- nav.removeAttribute('id'); nav.className = ''; // (not the TOC of the document any more, nor in the margin)
830
- add('\u2630', 'Contents', nav);
808
+ nav.removeAttribute('id'); nav.className = ''; // (not the TOC of the document, nor in the margin)
809
+ add('☰', 'Contents', nav);
831
810
  }
832
811
  if (bad.length) {
833
812
  const ul = make('ul', 'pagesjs-problems');
@@ -835,15 +814,18 @@
835
814
  const li = make('li');
836
815
  li.textContent = msg;
837
816
  li.onclick = () => {
838
- $('.' + hit)?.classList.remove(hit);
817
+ unhit();
839
818
  addCls(el, hit);
840
819
  el.scrollIntoView({block: 'center'});
841
820
  };
842
821
  ul.append(li);
843
822
  });
844
- add('\u26a0', 'Problems (may be cut off or overflow)', ul);
823
+ add('⚠', 'Problems (may be cut off or overflow)', ul);
845
824
  }
846
- tools.children.length && d.body.append(tools);
825
+ const print = toolButton(printer, 'Print this page', () => { closeAll(); window.print(); });
826
+ print.className = 'pagesjs-tool-print';
827
+ tools.append(print);
828
+ d.body.append(tools);
847
829
  on('keydown', e => e.key === 'Escape' && closeAll());
848
830
  on('click', e => tools.contains(e.target) || closeAll());
849
831
  }
@@ -854,30 +836,26 @@
854
836
  return [...el.childNodes].some(n => n.nodeType === 3 && n.nodeValue.trim());
855
837
  }
856
838
  function canBeRoot(el) { return !['PRE', 'TABLE'].includes(el.tagName) && !ownText(el); }
857
- // The content root is specified via <body data-pages-root="selector">, or is
858
- // <main> (or an element with role="main"), or the top-level <article> elements,
859
- // or <body>. If <main> only has a child (e.g., <article>), the child is the root
860
- // (and so on). Everything else (e.g., navigation bars) will be hidden.
839
+ // The content root: <body data-pages-root="selector">, else <main> (or role="main"), else
840
+ // the top-level <article>s, else <body>. If <main> only has a child (e.g., <article>), that
841
+ // child is the root (and so on). Everything else (e.g., navigation bars) is hidden.
861
842
  function findRoots() {
862
843
  const sel = d.body.dataset.pagesRoot, x = sel ? [...$$(sel)] : [];
863
844
  if (x.length) return x;
864
845
  let main = $('main, [role="main"]');
865
- // if it only contains a wrapper (e.g., an <article>), use the wrapper instead
866
- // (but not an element that is broken by its own, or has text, which would be lost)
846
+ // (not an element that is broken by its own, or has text, which would be lost)
867
847
  while (main && nChild(main) === 1 && !ownText(main) && canBeRoot(firstEl(main)))
868
848
  main = firstEl(main);
869
849
  if (main) return [main];
870
850
  const articles = [...$$('article')].filter(el => !el.parentNode.closest('article'));
871
851
  return articles.length ? articles : [d.body];
872
852
  }
873
- // The frontmatter (title, author, etc.) of the document is <header> (a child of
874
- // <body>) by default, or specified via <body data-pages-front="selector">; it is
875
- // put on its own page in a book.
853
+ // The frontmatter (title, author, etc.) is <header> directly in <body>, or
854
+ // <body data-pages-front="selector">; in a book it gets a page of its own.
876
855
  function markFrontmatter() {
877
856
  $$(d.body.dataset.pagesFront || 'body > header').forEach(el => addCls(el, 'pagesjs-front'));
878
857
  }
879
- // remove the classes of the TOC, footnotes, etc. that put them in the margin on
880
- // screen but are not suitable for printing
858
+ // remove the classes that put the TOC, footnotes, etc. in the margin on screen (not for print)
881
859
  function removeSideClasses() {
882
860
  // a wide element has a page of its own, so it is not full width
883
861
  $$('.pagesjs-wide.fullwidth').forEach(el => rmCls(el, 'fullwidth'));
@@ -885,10 +863,10 @@
885
863
  rmCls(el, 'side', 'side-left', 'side-right');
886
864
  });
887
865
  }
888
- // Replace the notes (footnotes and citations that sidenotes.js has put after their
889
- // references) with markers, which go with the references when the text is broken.
866
+ // Replace the notes (footnotes and citations that sidenotes.js put after their references)
867
+ // with markers, which go with the references when the text is broken.
890
868
  function detachNotes() {
891
- // (sidenotes.js puts them in a layer; bring each back after its reference)
869
+ // (sidenotes.js puts them in a layer: bring each back after its reference)
892
870
  $$('.footnotes[data-note-for]').forEach(el => d.getElementById(el.dataset.noteFor)?.after(el));
893
871
  $$('.sidenotes').forEach(el => el.remove());
894
872
  $$('.footnotes').forEach(el => {
@@ -899,30 +877,26 @@
899
877
  notes.set(m, kids(el)); el.replaceWith(m);
900
878
  });
901
879
  }
902
- // test how much space a single-line paragraph needs
880
+ // the space a single-line paragraph needs
903
881
  function measureMinHeight() {
904
882
  const p = make('p'), H0 = box.scrollHeight;
905
883
  p.innerText = 'A'; box_body.append(p);
906
884
  H_min = box.scrollHeight - H0; H_line = rect(p).height; p.remove();
907
885
  }
908
- // add dot leaders to TOC (page numbers will be added after the pages are ready)
886
+ // dot leaders for the TOC (page numbers are added when the pages are ready)
909
887
  function addTocLeaders() {
910
888
  $$('#TOC a[href^="#"]').forEach(a => {
911
- const s = make('span', 'toc-text'); // move TOC item content into a span
889
+ const s = make('span', 'toc-text'); // the item content goes into a span
912
890
  a.append(s);
913
- let c; while (c = s.previousSibling) {
914
- // exclude section number spans
915
- if (c.nodeType === 1 && has(c, 'section-number')) break; s.prepend(c);
916
- }
891
+ // (the section number stays out of the span)
892
+ for (let c; (c = s.previousSibling) && !(c.nodeType === 1 && has(c, 'section-number'));) s.prepend(c);
917
893
  a.dataset.pageNumber = '000'; // placeholder for page numbers
918
894
  });
919
895
  }
920
- // take the children of the roots out of the DOM (to speed up rendering single
921
- // pages), and return them
896
+ // take the children of the roots out of the DOM (to speed up rendering single pages), and return them
922
897
  function detachContent(roots) {
923
898
  return roots.map(el => {
924
- // move <style>/<link> into <head> so styles can be applied globally (not
925
- // only when they are in the DOM), no matter how deeply they are nested
899
+ // move <style>/<link> into <head>, so styles apply globally, however deep they are
926
900
  $$('style, link[rel="stylesheet"]', el).forEach(el => d.head.append(el));
927
901
  const ch = kids(el).filter(el => ![box, hold, progress].includes(el) &&
928
902
  !['SCRIPT', 'NOSCRIPT', 'TEMPLATE'].includes(el.tagName));
@@ -933,13 +907,13 @@
933
907
  // iteratively add elements to pages
934
908
  function* fillPages(roots, els) {
935
909
  for (const el of $$('.pagesjs-front, .abstract, #TOC:not(.chapter-toc)')) {
936
- // mark the first page if it has the frontmatter (for styling; :has() would be re-checked on every change)
910
+ // (class on the page, since :has() would be re-checked on every change)
937
911
  has(el, 'pagesjs-front') && box === boxes[0] && addCls(box, 'page-front');
938
912
  yield* fill(el);
939
913
  book && nextPage();
940
914
  }
941
915
  for (const [i, el] of roots.entries()) {
942
- wrap = ancestors(el); box_ctx = null;
916
+ setRoot(el);
943
917
  book && (box.innerText === '' ? newPage(box) : nextPage());
944
918
  const list = els[i];
945
919
  for (let j = 0; j < list.length; j++) {
@@ -949,15 +923,15 @@
949
923
  run.length && (ctx().append(...run), overflows() ? run.forEach(e => e.remove()) : j += run.length);
950
924
  }
951
925
  flush();
952
- // clean up container and self if empty
926
+ // clean up the container and self if empty
953
927
  removeBlank(el.parentNode); removeBlank(el);
954
928
  }
955
929
  finish(box); // finish the last box
956
- // unwrap the blocks created for runs of inline nodes
930
+ // unwrap the blocks made for runs of inline nodes
957
931
  $$('.pagesjs-run').forEach(el => el.replaceWith(...el.childNodes));
958
932
  }
959
- // Run the rest of the pagination. If it is not sync, do it in slices of 0.5s,
960
- // so the browser can show the progress in between (not too often, to save time).
933
+ // Run the rest of the pagination. Unless sync, do it in slices of 0.5s, so the browser can
934
+ // paint the progress in between.
961
935
  function advance(sync) {
962
936
  const t = performance.now();
963
937
  while (!running.next().done) {
@@ -969,7 +943,7 @@
969
943
  function paginate(sync) {
970
944
  // nobody sees the progress in a headless browser (and printing has to be sync)
971
945
  const quiet = sync || /Headless/.test(navigator.userAgent) || navigator.webdriver;
972
- // we need to wait for all resources to be fully loaded before paginating
946
+ // all resources must be loaded before paginating
973
947
  if (d.readyState !== 'complete') return on('load', () => paginate(sync));
974
948
 
975
949
  const cls = d.body.classList;
@@ -978,18 +952,19 @@
978
952
  const t0 = performance.now();
979
953
 
980
954
  markFrontmatter();
981
- // (get the title while the document is visible, so innerText works)
955
+ // (the title is read while the document is visible, so innerText works)
982
956
  main_title = shortTitle($('h1.title, .pagesjs-front h1, .title, h1'));
983
957
 
984
958
  cls.add('pagesjs');
959
+ $$('.pagesjs-tools, .pagesjs-print').forEach(el => el.remove()); // (addTools() makes new tools)
985
960
  d.body.append(hold);
986
- if (!quiet) { // a simple indicator to tell users to wait
961
+ if (!quiet) {
987
962
  progress = make('div', 'pagesjs-progress');
988
963
  progress.textContent = 'Paginating...';
989
964
  d.body.append(progress);
990
965
  }
991
966
  d.body.insertAdjacentElement('afterbegin', newPage());
992
- // (use window height if box height not specified)
967
+ // (the window height if the box height is not set)
993
968
  const size = () => { const h = (box.clientHeight || window.innerHeight) + tol; return [h, box_body.clientHeight || h]; };
994
969
  portrait = size();
995
970
  addCls(box, 'page-wide'); landscape = size(); rmCls(box, 'page-wide');
@@ -1016,9 +991,8 @@
1016
991
  (over ? `; ${over} overflow their page` : ''));
1017
992
  fire('pagesjs:after');
1018
993
  }
1019
- // Pagination is async unless it has to be sync (beforeprint). If printing
1020
- // starts while it's pending (e.g., headless printing right after the page is
1021
- // loaded), finish it right away.
994
+ // Async unless it has to be sync (beforeprint). If printing starts while it is pending
995
+ // (e.g., headless printing right after load), finish it right away.
1022
996
  pending = sync => { pending = null; unprobe(); running = run(); return advance(sync || quiet); };
1023
997
  sync ? pending(true) : probe(roots, els).then(() => pending?.());
1024
998
  }
@@ -1027,23 +1001,23 @@
1027
1001
  else if (running) while (!running.next().done); // finish the pagination in progress
1028
1002
  else paginate(true);
1029
1003
  });
1030
- // A script that controls the browser can request the pagination by dispatching
1031
- // pagesjs:paginate, and wait for pagesjs:after (which is also dispatched if the
1032
- // pagination was already finished)
1004
+ // A script that controls the browser can dispatch pagesjs:paginate and wait for
1005
+ // pagesjs:after (also dispatched if the pagination was already finished)
1033
1006
  on('pagesjs:paginate', () => {
1034
1007
  finished ? fire('pagesjs:after') : paginate();
1035
1008
  });
1036
- // use query param ?paged=1 to indicate pagination (press p to toggle)
1037
- const SP = new URLSearchParams(location.search);
1009
+ // ?paged=1 requests the pagination; an unpaginated page gets a button to start it
1038
1010
  SP.get('paged') && paginate();
1039
- on('keypress', e => {
1040
- if (e.key === 'p') {
1041
- if (SP.get('paged')) {
1042
- SP.delete('paged'); location.href = location.pathname + (SP.size ? `?${SP}` : '');
1043
- } else {
1044
- paginate();
1045
- SP.set('paged', 1); history.replaceState({}, '', `${location.pathname}?${SP}`);
1046
- }
1047
- }
1048
- });
1011
+ // Back/Forward between the unpaginated and paged views (entries of the same document)
1012
+ // need a reload, since the content has been moved onto pages
1013
+ on('popstate', () => new URLSearchParams(location.search).get('paged') != SP.get('paged') && location.reload());
1014
+ function addToggle() {
1015
+ if (finished || has(d.body, 'pagesjs') || noToggle()) return;
1016
+ // a page can reserve a place for the button with <span class="pagesjs-toggle"></span>;
1017
+ // otherwise it floats at the top left
1018
+ const slot = $('.pagesjs-toggle'), tools = slot || make('div', 'pagesjs-tools');
1019
+ tools.append(pagedButton());
1020
+ slot || d.body.append(tools);
1021
+ }
1022
+ if (!SP.get('paged')) d.readyState === 'loading' ? d.addEventListener('DOMContentLoaded', addToggle) : addToggle();
1049
1023
  })(document);