@xiee/utils 1.14.154 → 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/README.md +2 -1
- package/css/pages.css +2 -1
- package/css/pages.min.css +1 -1
- package/css/pages.min.css.map +1 -1
- package/css/pkgdown-like.css +1 -1
- package/css/pkgdown-like.min.css +1 -1
- package/css/pkgdown-like.min.css.map +1 -1
- package/css/site.css +13 -1
- package/css/site.min.css +1 -1
- package/css/site.min.css.map +1 -1
- package/js/nav-highlight.js +2 -1
- package/js/nav-highlight.min.js +1 -1
- package/js/nav-highlight.min.js.map +1 -1
- package/js/pages.js +286 -317
- package/js/pages.min.js +1 -1
- package/js/pages.min.js.map +1 -1
- package/package.json +1 -1
package/js/pages.js
CHANGED
|
@@ -1,36 +1,24 @@
|
|
|
1
|
-
// Paginate an HTML page
|
|
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
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
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
|
|
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, //
|
|
58
|
-
//
|
|
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
|
-
//
|
|
63
|
-
//
|
|
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
|
|
66
|
-
//
|
|
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
|
|
77
|
-
guessed = new WeakSet(), // pages whose number of physical pages is
|
|
78
|
-
floats = [], //
|
|
79
|
-
notes = new Map(), //
|
|
80
|
-
probeY = new WeakMap(), //
|
|
81
|
-
hold = make('div'); //
|
|
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 (
|
|
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 (
|
|
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
|
|
95
|
-
whole, // the float that takes the page
|
|
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
|
|
98
|
-
pending, // the rest of the pagination,
|
|
99
|
-
running, // the generator that does the rest of the pagination (
|
|
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
|
|
85
|
+
finished, // is the pagination finished?
|
|
86
|
+
SP = new URLSearchParams(location.search);
|
|
102
87
|
|
|
103
|
-
// Diagnosis: pages that overflow, elements with
|
|
104
|
-
// stick out of the page
|
|
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
|
-
|
|
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);
|
|
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
|
|
137
|
-
//
|
|
138
|
-
//
|
|
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
|
-
//
|
|
150
|
-
|
|
151
|
-
|
|
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
|
-
//
|
|
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
|
-
//
|
|
158
|
-
//
|
|
159
|
-
//
|
|
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
|
|
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
|
|
184
|
-
//
|
|
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
|
-
//
|
|
193
|
-
//
|
|
194
|
-
//
|
|
195
|
-
//
|
|
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
|
-
//
|
|
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
|
|
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');
|
|
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
|
-
//
|
|
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
|
-
//
|
|
238
|
+
// a page element is used as the box
|
|
258
239
|
if (has(el, 'pagesjs-page')) {
|
|
259
240
|
nextPage(el, () => nChild(el) > 3 && (
|
|
260
|
-
//
|
|
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
|
-
|
|
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
|
|
274
|
-
// the
|
|
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
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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
|
|
297
|
-
//
|
|
298
|
-
//
|
|
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
|
-
// (
|
|
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
|
-
|
|
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
|
|
317
|
-
//
|
|
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
|
-
//
|
|
326
|
-
//
|
|
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
|
|
333
|
-
//
|
|
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
|
-
//
|
|
341
|
-
//
|
|
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
|
-
//
|
|
351
|
-
//
|
|
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
|
|
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
|
|
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
|
|
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>;
|
|
399
|
-
//
|
|
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
|
|
411
|
-
//
|
|
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,
|
|
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
|
|
428
|
-
//
|
|
429
|
-
//
|
|
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 (
|
|
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
|
-
//
|
|
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
|
|
413
|
+
// computed styles are only available in the DOM
|
|
447
414
|
el.isConnected || hold.append(el);
|
|
448
415
|
let run = [];
|
|
449
|
-
function
|
|
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) :
|
|
457
|
-
|
|
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
|
|
466
|
-
//
|
|
467
|
-
//
|
|
468
|
-
//
|
|
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
|
|
489
|
-
//
|
|
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
|
-
//
|
|
520
|
-
// block or above a table)
|
|
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
|
-
//
|
|
527
|
-
//
|
|
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
|
|
535
|
-
//
|
|
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
|
|
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,
|
|
545
|
-
//
|
|
546
|
-
//
|
|
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> (
|
|
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
|
|
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
|
|
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,
|
|
583
|
-
//
|
|
584
|
-
|
|
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 (
|
|
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
|
|
595
|
-
//
|
|
596
|
-
function newLine(
|
|
597
|
-
return prev && prev.bottom <=
|
|
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
|
|
565
|
+
node = walker.nextSibling(); // skip blocks, floats (footnotes), and math
|
|
604
566
|
if (!node) break;
|
|
605
567
|
}
|
|
606
|
-
if (node.firstChild) continue; //
|
|
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
|
|
614
|
-
//
|
|
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
|
|
626
|
-
function
|
|
627
|
-
let lo = 0, hi =
|
|
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
|
-
|
|
631
|
-
r.getClientRects().length > k ? hi = mid : lo = mid + 1;
|
|
592
|
+
test(mid) ? hi = mid : lo = mid + 1;
|
|
632
593
|
}
|
|
633
|
-
return lo
|
|
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.
|
|
636
|
-
//
|
|
637
|
-
//
|
|
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 (
|
|
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
|
-
|
|
661
|
-
if
|
|
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
|
|
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
|
-
//
|
|
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
|
|
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
|
-
//
|
|
702
|
-
//
|
|
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
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
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
|
|
741
|
-
//
|
|
742
|
-
//
|
|
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
|
-
|
|
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 = '';
|
|
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
|
-
//
|
|
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
|
|
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
|
-
//
|
|
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
|
-
//
|
|
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,47 @@
|
|
|
809
764
|
});
|
|
810
765
|
}
|
|
811
766
|
|
|
812
|
-
//
|
|
813
|
-
|
|
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.
|
|
814
791
|
function addTools() {
|
|
815
792
|
const tools = make('div', 'pagesjs-tools'), toc = $('#TOC:not(.chapter-toc)'), bad = problems();
|
|
816
793
|
const closeAll = () => {
|
|
817
794
|
$$('.pagesjs-panel', tools).forEach(p => p.hidden = true);
|
|
818
|
-
|
|
795
|
+
unhit();
|
|
819
796
|
};
|
|
820
797
|
function add(text, title, content) {
|
|
821
|
-
const btn =
|
|
822
|
-
|
|
798
|
+
const btn = toolButton(text, title), panel = make('div', 'pagesjs-panel');
|
|
799
|
+
panel.hidden = true; panel.append(content);
|
|
823
800
|
btn.onclick = () => { const was = panel.hidden; closeAll(); panel.hidden = !was; };
|
|
824
801
|
tools.append(btn, panel);
|
|
825
802
|
return panel;
|
|
826
803
|
}
|
|
827
804
|
if (toc) {
|
|
828
805
|
const nav = toc.cloneNode(true);
|
|
829
|
-
nav.removeAttribute('id'); nav.className = ''; // (not the TOC of the document
|
|
830
|
-
add('
|
|
806
|
+
nav.removeAttribute('id'); nav.className = ''; // (not the TOC of the document, nor in the margin)
|
|
807
|
+
add('☰', 'Contents', nav);
|
|
831
808
|
}
|
|
832
809
|
if (bad.length) {
|
|
833
810
|
const ul = make('ul', 'pagesjs-problems');
|
|
@@ -835,13 +812,13 @@
|
|
|
835
812
|
const li = make('li');
|
|
836
813
|
li.textContent = msg;
|
|
837
814
|
li.onclick = () => {
|
|
838
|
-
|
|
815
|
+
unhit();
|
|
839
816
|
addCls(el, hit);
|
|
840
817
|
el.scrollIntoView({block: 'center'});
|
|
841
818
|
};
|
|
842
819
|
ul.append(li);
|
|
843
820
|
});
|
|
844
|
-
add('
|
|
821
|
+
add('⚠', 'Problems (may be cut off or overflow)', ul);
|
|
845
822
|
}
|
|
846
823
|
tools.children.length && d.body.append(tools);
|
|
847
824
|
on('keydown', e => e.key === 'Escape' && closeAll());
|
|
@@ -854,30 +831,26 @@
|
|
|
854
831
|
return [...el.childNodes].some(n => n.nodeType === 3 && n.nodeValue.trim());
|
|
855
832
|
}
|
|
856
833
|
function canBeRoot(el) { return !['PRE', 'TABLE'].includes(el.tagName) && !ownText(el); }
|
|
857
|
-
// The content root
|
|
858
|
-
// <
|
|
859
|
-
//
|
|
860
|
-
// (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.
|
|
861
837
|
function findRoots() {
|
|
862
838
|
const sel = d.body.dataset.pagesRoot, x = sel ? [...$$(sel)] : [];
|
|
863
839
|
if (x.length) return x;
|
|
864
840
|
let main = $('main, [role="main"]');
|
|
865
|
-
//
|
|
866
|
-
// (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)
|
|
867
842
|
while (main && nChild(main) === 1 && !ownText(main) && canBeRoot(firstEl(main)))
|
|
868
843
|
main = firstEl(main);
|
|
869
844
|
if (main) return [main];
|
|
870
845
|
const articles = [...$$('article')].filter(el => !el.parentNode.closest('article'));
|
|
871
846
|
return articles.length ? articles : [d.body];
|
|
872
847
|
}
|
|
873
|
-
// The frontmatter (title, author, etc.)
|
|
874
|
-
// <body
|
|
875
|
-
// 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.
|
|
876
850
|
function markFrontmatter() {
|
|
877
851
|
$$(d.body.dataset.pagesFront || 'body > header').forEach(el => addCls(el, 'pagesjs-front'));
|
|
878
852
|
}
|
|
879
|
-
// remove the classes
|
|
880
|
-
// 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)
|
|
881
854
|
function removeSideClasses() {
|
|
882
855
|
// a wide element has a page of its own, so it is not full width
|
|
883
856
|
$$('.pagesjs-wide.fullwidth').forEach(el => rmCls(el, 'fullwidth'));
|
|
@@ -885,10 +858,10 @@
|
|
|
885
858
|
rmCls(el, 'side', 'side-left', 'side-right');
|
|
886
859
|
});
|
|
887
860
|
}
|
|
888
|
-
// Replace the notes (footnotes and citations that sidenotes.js
|
|
889
|
-
//
|
|
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.
|
|
890
863
|
function detachNotes() {
|
|
891
|
-
// (sidenotes.js puts them in a layer
|
|
864
|
+
// (sidenotes.js puts them in a layer: bring each back after its reference)
|
|
892
865
|
$$('.footnotes[data-note-for]').forEach(el => d.getElementById(el.dataset.noteFor)?.after(el));
|
|
893
866
|
$$('.sidenotes').forEach(el => el.remove());
|
|
894
867
|
$$('.footnotes').forEach(el => {
|
|
@@ -899,30 +872,26 @@
|
|
|
899
872
|
notes.set(m, kids(el)); el.replaceWith(m);
|
|
900
873
|
});
|
|
901
874
|
}
|
|
902
|
-
//
|
|
875
|
+
// the space a single-line paragraph needs
|
|
903
876
|
function measureMinHeight() {
|
|
904
877
|
const p = make('p'), H0 = box.scrollHeight;
|
|
905
878
|
p.innerText = 'A'; box_body.append(p);
|
|
906
879
|
H_min = box.scrollHeight - H0; H_line = rect(p).height; p.remove();
|
|
907
880
|
}
|
|
908
|
-
//
|
|
881
|
+
// dot leaders for the TOC (page numbers are added when the pages are ready)
|
|
909
882
|
function addTocLeaders() {
|
|
910
883
|
$$('#TOC a[href^="#"]').forEach(a => {
|
|
911
|
-
const s = make('span', 'toc-text'); //
|
|
884
|
+
const s = make('span', 'toc-text'); // the item content goes into a span
|
|
912
885
|
a.append(s);
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
if (c.nodeType === 1 && has(c, 'section-number')) break; s.prepend(c);
|
|
916
|
-
}
|
|
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);
|
|
917
888
|
a.dataset.pageNumber = '000'; // placeholder for page numbers
|
|
918
889
|
});
|
|
919
890
|
}
|
|
920
|
-
// take the children of the roots out of the DOM (to speed up rendering single
|
|
921
|
-
// pages), and return them
|
|
891
|
+
// take the children of the roots out of the DOM (to speed up rendering single pages), and return them
|
|
922
892
|
function detachContent(roots) {
|
|
923
893
|
return roots.map(el => {
|
|
924
|
-
// move <style>/<link> into <head
|
|
925
|
-
// 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
|
|
926
895
|
$$('style, link[rel="stylesheet"]', el).forEach(el => d.head.append(el));
|
|
927
896
|
const ch = kids(el).filter(el => ![box, hold, progress].includes(el) &&
|
|
928
897
|
!['SCRIPT', 'NOSCRIPT', 'TEMPLATE'].includes(el.tagName));
|
|
@@ -933,13 +902,13 @@
|
|
|
933
902
|
// iteratively add elements to pages
|
|
934
903
|
function* fillPages(roots, els) {
|
|
935
904
|
for (const el of $$('.pagesjs-front, .abstract, #TOC:not(.chapter-toc)')) {
|
|
936
|
-
//
|
|
905
|
+
// (class on the page, since :has() would be re-checked on every change)
|
|
937
906
|
has(el, 'pagesjs-front') && box === boxes[0] && addCls(box, 'page-front');
|
|
938
907
|
yield* fill(el);
|
|
939
908
|
book && nextPage();
|
|
940
909
|
}
|
|
941
910
|
for (const [i, el] of roots.entries()) {
|
|
942
|
-
|
|
911
|
+
setRoot(el);
|
|
943
912
|
book && (box.innerText === '' ? newPage(box) : nextPage());
|
|
944
913
|
const list = els[i];
|
|
945
914
|
for (let j = 0; j < list.length; j++) {
|
|
@@ -949,15 +918,15 @@
|
|
|
949
918
|
run.length && (ctx().append(...run), overflows() ? run.forEach(e => e.remove()) : j += run.length);
|
|
950
919
|
}
|
|
951
920
|
flush();
|
|
952
|
-
// clean up container and self if empty
|
|
921
|
+
// clean up the container and self if empty
|
|
953
922
|
removeBlank(el.parentNode); removeBlank(el);
|
|
954
923
|
}
|
|
955
924
|
finish(box); // finish the last box
|
|
956
|
-
// unwrap the blocks
|
|
925
|
+
// unwrap the blocks made for runs of inline nodes
|
|
957
926
|
$$('.pagesjs-run').forEach(el => el.replaceWith(...el.childNodes));
|
|
958
927
|
}
|
|
959
|
-
// Run the rest of the pagination.
|
|
960
|
-
//
|
|
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.
|
|
961
930
|
function advance(sync) {
|
|
962
931
|
const t = performance.now();
|
|
963
932
|
while (!running.next().done) {
|
|
@@ -969,7 +938,7 @@
|
|
|
969
938
|
function paginate(sync) {
|
|
970
939
|
// nobody sees the progress in a headless browser (and printing has to be sync)
|
|
971
940
|
const quiet = sync || /Headless/.test(navigator.userAgent) || navigator.webdriver;
|
|
972
|
-
//
|
|
941
|
+
// all resources must be loaded before paginating
|
|
973
942
|
if (d.readyState !== 'complete') return on('load', () => paginate(sync));
|
|
974
943
|
|
|
975
944
|
const cls = d.body.classList;
|
|
@@ -978,18 +947,19 @@
|
|
|
978
947
|
const t0 = performance.now();
|
|
979
948
|
|
|
980
949
|
markFrontmatter();
|
|
981
|
-
// (
|
|
950
|
+
// (the title is read while the document is visible, so innerText works)
|
|
982
951
|
main_title = shortTitle($('h1.title, .pagesjs-front h1, .title, h1'));
|
|
983
952
|
|
|
984
953
|
cls.add('pagesjs');
|
|
954
|
+
$$('.pagesjs-tools, .pagesjs-print').forEach(el => el.remove()); // (addTools() makes new tools)
|
|
985
955
|
d.body.append(hold);
|
|
986
|
-
if (!quiet) {
|
|
956
|
+
if (!quiet) {
|
|
987
957
|
progress = make('div', 'pagesjs-progress');
|
|
988
958
|
progress.textContent = 'Paginating...';
|
|
989
959
|
d.body.append(progress);
|
|
990
960
|
}
|
|
991
961
|
d.body.insertAdjacentElement('afterbegin', newPage());
|
|
992
|
-
// (
|
|
962
|
+
// (the window height if the box height is not set)
|
|
993
963
|
const size = () => { const h = (box.clientHeight || window.innerHeight) + tol; return [h, box_body.clientHeight || h]; };
|
|
994
964
|
portrait = size();
|
|
995
965
|
addCls(box, 'page-wide'); landscape = size(); rmCls(box, 'page-wide');
|
|
@@ -1016,9 +986,8 @@
|
|
|
1016
986
|
(over ? `; ${over} overflow their page` : ''));
|
|
1017
987
|
fire('pagesjs:after');
|
|
1018
988
|
}
|
|
1019
|
-
//
|
|
1020
|
-
//
|
|
1021
|
-
// 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.
|
|
1022
991
|
pending = sync => { pending = null; unprobe(); running = run(); return advance(sync || quiet); };
|
|
1023
992
|
sync ? pending(true) : probe(roots, els).then(() => pending?.());
|
|
1024
993
|
}
|
|
@@ -1027,23 +996,23 @@
|
|
|
1027
996
|
else if (running) while (!running.next().done); // finish the pagination in progress
|
|
1028
997
|
else paginate(true);
|
|
1029
998
|
});
|
|
1030
|
-
// A script that controls the browser can
|
|
1031
|
-
// pagesjs:
|
|
1032
|
-
// 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)
|
|
1033
1001
|
on('pagesjs:paginate', () => {
|
|
1034
1002
|
finished ? fire('pagesjs:after') : paginate();
|
|
1035
1003
|
});
|
|
1036
|
-
//
|
|
1037
|
-
const SP = new URLSearchParams(location.search);
|
|
1004
|
+
// ?paged=1 requests the pagination; an unpaginated page gets a button to start it
|
|
1038
1005
|
SP.get('paged') && paginate();
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
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();
|
|
1049
1018
|
})(document);
|