@xiee/utils 1.14.153 → 1.14.155

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