22925e6119d9c68d7223031fac3b1ad8be4f1513
Pagination / pagination.js
/*

The MIT License (MIT)

Copyright © 2023 Dean Lee

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

//global constant values

const styleString = `
body {margin: 0; padding: 0;}
.pages {
  text-rendering: geometricPrecision;
  background-color: #555555;
  margin: 0;
  padding: 20mm 0;
}
.hiphip_page {
  box-sizing: border-box;
  width: 210mm;
  height: 297mm;
  margin-left: auto;
  margin-right: auto;
  margin-top: 0;
  margin-bottom: 20mm;
  padding: 0;
  border-width: 0;
}
.hiphip_sheet {
  background-color: #ffffff;
  box-sizing: border-box;
  border-width: 0;
  padding: 0;
  margin: 0;
  width: 210mm;
  height: 297mm;
  overflow: hidden;
}
.hiphip_pagebox {
  box-sizing: border-box;
  border-width: 0;
  margin: 0;
  width: 210mm;
  height: 297mm;
  overflow: hidden;
  display: grid;
  grid-template-columns: [left] 25mm [center] 160mm [right] 25mm;
  grid-template-rows: [header] 30mm [page] 237mm [footer] 30mm;
}
.hiphip_margin-top {
  grid-column: center;
  grid-row: header;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: 100%;
}
.hiphip_margin-top-left-corner-holder {
  grid-column: left;
  grid-row: header;
}
.hiphip_margin-top-right-corner-holder
  grid-column: right;
  grid-row: header;
}
.hiphip_margin-right {
  grid-column: right;
  grid-row: page;
}
.hiphip_margin-left {
  grid-column: left;
  grid-row: page;
}
.hiphip_margin-bottom {
  grid-column: center;
  grid-row: footer;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: 100%;
}
.hiphip_margin-bottom-left-corner-holder {
  grid-column: left;
  grid-row: footer;
}
.hiphip_margin-bottom-right-corner-holder {
  grid-column: right;
  grid-row: footer;
}
.hiphip_area {
  grid-column: center;
  grid-row: page;
}
.hiphip_page-content {
  width: 100%;
  height: 100%;
  column-fill: auto;
  column-width: 170mm;
  column-gap: 40mm;
  line-height: 1.6em;
}
.hiphip_margin-bottom-center {
  text-align: center;
  margin-top: 10%;
  margin-bottom: auto;
}
@media print {@page {margin: 0; padding 0;} .pages {margin: 0; padding: 0;} .hiphip_page {margin: 0;}}
`

const templateString = `
<div class="hiphip_page">
    <div class="hiphip_sheet">
        <div class="hiphip_pagebox">
            <div class="hiphip_margin-top-left-corner-holder">
            </div>
            <div class="hiphip_margin-top">
                <div class="hiphip_margin hiphip_margin-top-left"><div class="hiphip_margin-content"></div></div>
                <div class="hiphip_margin hiphip_margin-top-center"><div class="hiphip_margin-content"></div></div>
                <div class="hiphip_margin hiphip_margin-top-right"><div class="hiphip_margin-content"></div></div>
            </div>
            <div class="hiphip_margin-top-right-corner-holder">
            </div>
            <div class="hiphip_margin-right">
            </div>
            <div class="hiphip_margin-left">
            </div>
            <div class="hiphip_margin-bottom-left-corner-holder">
            </div>
            <div class="hiphip_margin-bottom">
                <div class="hiphip_margin hiphip_margin-bottom-left"><div class="hiphip_margin-content"></div></div>
                <div class="hiphip_margin hiphip_margin-bottom-center"><div class="hiphip_margin-content"></div></div>
                <div class="hiphip_margin hiphip_margin-bottom-right"><div class="hiphip_margin-content"></div></div>
            </div>
            <div class="hiphip_margin-bottom-right-corner-holder">
            </div>
            <div class="hiphip_area">
                <div class="hiphip_page-content"></div>
            </div>
        </div>
    </div>
</div>`

const head = document.querySelector('head');
const body = document.querySelector('body');
const headingElements = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'];
const blockElements = ['DIV', 'P', 'OL', 'UL', 'LI', 'BLOCKQUOTE', 'HR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'];
const safetyGap = 20; // exaggerate coordinates to avoid overlap etc.

// fundamental utilities

const push = (item) => (array) => {
    array.push(item);
    return array;
}

const tail = (list) => {
    Array.prototype.shift.call(list);
    return list;
}

function pipe() { // "arguments" does not work with the lambda
    let recursion = (value, funcs) => funcs.length === 0 ? value : recursion(funcs[0](value), tail(funcs));
    return recursion(arguments[0], tail(arguments));
}

const increment = (index) => ++index;

// DOM utilities

const parentNode = (node) => node.parentNode;
const previousSibling = (node) => node.previousSibling;
const previousElementSibling = (element) => element.previousElementSibling;
const nextSibling = (node) => node.nextSibling;
const nextElementSibling = (element) => element.nextElementSibling;
const firstChild = (node) => node.firstChild;
const firstElementChild = (element) => element.firstElementChild;
const lastChild = (node) => node.lastChild;
const lastElementChild = (element) => element.lastElementChild;
const findDeepest = (childType) => (node) => !childType(node) ? node : pipe(childType(node), findDeepest(childType));
const climbToSibling = (siblingType) => (node) => siblingType(node) || isTop(node) ? node : pipe(parentNode(node), climbToSibling(siblingType));

const nearestCousin = (siblingType) => (node) => {
    let childType = siblingType === nextSibling ? firstChild : lastChild;
    let top = climbToSibling(siblingType)(node);
    let sibling = siblingType(top);
    return !sibling ? false : findDeepest(childType)(sibling);
}

const previousCousin = (node) => nearestCousin(previousSibling)(node);
const nextCousin = (node) => nearestCousin(nextSibling)(node);

const listRelatives = (relativeType) => (node) => {
    let recursion = (node, acc = []) => {
        let newAcc = push(node)(acc);
        let newNode = relativeType(node);
        return !newNode ? newAcc : recursion(newNode, newAcc);
    }
    return recursion(node);
}

const importNode = (node) => document.importNode(node, true);
const createElement = (name) => document.createElement(name);

const addClass = (className) => (element) => {
    element.classList.add(className);
    return element;
}

const setFlag = (flag) => (element) => {
    element.setAttribute(flag, 'true');
    return element;
}

const append = (node) => (dest) => {
    dest.appendChild(node);
    return dest;
}

const appendTo = (dest) => (node) => {
    dest.appendChild(node);
    return dest.lastChild;
}

const insertBefore = (reference) => (node) => {
    parentNode(reference).insertBefore(node, reference);
    return node;
}

const innerHTML = (content) => (element) => {
    element.innerHTML = content;
    return element;
}

const cloneElement = (element) => {
    let clone = element.cloneNode(false);
    setFlag('data-clone')(clone);
    if (clone.id) {
        clone.id = clone.id + '-cl';
    }
    return clone;
}

// text processing utilities

class TextSection {
    constructor(node, start, end) {
        this.node = node;
        this.start = start;
        this.end = end;
    }

    midRange (start, end) {
        return Math.floor(start + ((end - start) / 2));
    }
  
    copyFirstHalf() {
        return new TextSection(this.node, this.start, this.midRange(this.start, this.end));
    }
  
    copySecondHalf() {
        return new TextSection(this.node, this.midRange(this.start, this.end) + 1, this.end);
    }
  
    copyShiftLeft() {
        return new TextSection(this.node, this.start - 1, this.end - 1);
    }

    wrapInRange() {
        let range = document.createRange();
        range.setStart(this.node, this.start);
        range.setEnd(this.node, this.end + 1);
        return range;
    }
  
    getLeft() {
        return this.wrapInRange().getBoundingClientRect().left;
    }
  
    getRight() {
        return this.wrapInRange().getBoundingClientRect().right;
    }
}

const getNode = (textSection) => textSection.node;
const getfirstChar = (node) => new TextSection(node, 0, 0);
const getLastChar = (node) => new TextSection(node, node.data.length - 1, node.data.length - 1);

const getTextSection = (node) => {
    let end = isText(node) ? node.data.length - 1 : 0;
    return new TextSection(node, 0, end);
}

const getRectArray = (range) => {
    let pseudoArray = range.getClientRects();
    return Array.prototype.slice.call(pseudoArray, 0);
}

const wrapInRange = (node) => {
    let range = document.createRange();
    range.selectNode(node);
    return range;
}

const getRects = (element) => {
    let nodes = pipe(element, findDeepest(firstChild), listRelatives(nextCousin));
    let rectArrays = nodes.map((x) => pipe(x, wrapInRange, getRectArray));
    return rectArrays.reduce((a, b) => a.concat(b));
}

const getRight = (node) => {
    let rect = isElement(node) ? node.getBoundingClientRect() : wrapInRange(node).getBoundingClientRect();
    return rect.right;
}

// node information booleans

const isElement = (node) => node.nodeType === 1;
const isText = (node) => node.nodeType === 3;
const hasFlag = (flag) => (node) => !isElement(node) ? false : node.getAttribute(flag);
const isHeading = (element) => headingElements.some((x) => x === element.nodeName);
const isBlock = (element) => blockElements.some((x) => x === element.nodeName);
const isLi = (element) => element.nodeName === 'LI';
const isTop = (node) => hasFlag('data-top')(node);
const isMerger = (node) => hasFlag('data-merger')(node);

// misc utilities

const mark = (node) => { // for testing; beautiful way to track element traversal in pipes!
    if (isElement(node)) {  // e.g. pipe(node, mark, oFBlock)
        setFlag('x')(node);
    }
    return node;
}

const styleContent = () => document.createTextNode(styleString);
const getPageContent = (page) => page.querySelector('.hiphip_page-content');

// source preparation

const finishedMerger = (merger) => !pipe(merger, lastChild, isHeading) || !nextElementSibling(merger);
const createMerger = (element) => pipe(createElement('div'), insertBefore(element), setFlag('data-merger'), append(element));
const mergeNext = (merger) => pipe(merger, nextElementSibling, appendTo(merger), parentNode);

const mergeHeadings = (element) => {
    let recursion = (merger) => finishedMerger(merger) ? merger : pipe(merger, mergeNext, recursion);
    return !isHeading(element) ? element : pipe(element, createMerger, recursion);
}

const getSource = () => {
    let recursion = (element, acc = []) => {
        let current = mergeHeadings(element);
        let newAcc = push(current)(acc);
        let nextElement = nextElementSibling(current);
        return !nextElement ? newAcc : recursion(nextElement, newAcc);
    }
    return pipe(body, firstElementChild, recursion);
}

// page creation

const brake = (page) => { // to prevent accidental infinite page generation
    if (pages.childElementCount > 1000) {
        throw 'Page limit exceeded.';
    }
    return page;
}

const setIndex = (index) => (page) => {
    page.setAttribute('data-index', index);
    return page;
}

const getIndex = (page) => page.getAttribute('data-index');
const setPageNum = (page) => {page.querySelector('.hiphip_margin-bottom-center > div').innerHTML = getIndex(page)};
const addTemplate = () => pipe(template.content, importNode, appendTo(pages));

const setWrapper = (page) => {
    let pageContent = getPageContent(page);
    pipe(createElement('div'), addClass('wrapper'), appendTo(pageContent));
    return page;
}

const addPage = () => pipe(addTemplate(), setWrapper, brake);
const createFirstPage = () => pipe(addPage(), setIndex(1));

const newPage = () => {
    let page = addPage();
    let pageNumber = pipe(page, previousElementSibling, getIndex, increment);
    pipe(page, setIndex(pageNumber), setPageNum);    
}

const addToPage = (node) => {
    let target = document.querySelector('.hiphip_page:last-child .wrapper');
    return pipe(node, appendTo(target));
}

// overflow handling

const detectOverflow = (node) => getRight(node) > areaRight;
const containsBlock = (node) => !firstElementChild(node) ? false : pipe(node, firstElementChild, isBlock);
const firstOF = (node) => detectOverflow(node) ? node : pipe(node, nextSibling, firstOF);
const oFNode = (node) => !firstChild(node) || isLi(node) ? node : pipe(node, firstChild, firstOF, oFNode);
const oFBlock = (node) => !containsBlock(node) || isMerger(node) || isLi(node) ? node : pipe(node, firstElementChild, firstOF, oFBlock);
const findOverflow = (node) => pipe(node, oFBlock, climbToSibling(previousSibling));

const findOFHalf = (x) => {
    let firstHalf = x.copyFirstHalf();
    return firstHalf.getRight() > areaRight ? firstHalf : x.copySecondHalf();
}

const oFChar = (node) => {
    let recursion = (x) => x.start === x.end ? x : pipe(x, findOFHalf, recursion);
    let textSection = getTextSection(node);
    return isText(textSection.node) ? recursion(textSection) : textSection;
}

const pinpointOverflow = (element) => pipe(element, oFNode, oFChar);

// content division

const orphansAndWidows = (element) => {
    let rects = getRects(element);
    let oneRectPerLine = (x,i,a) => i === a.length - 1 ? true : (x.right - safetyGap) > a[i + 1].left; // safetyGap necessary to prevent accidental single widows
    let orphans = rects.filter((x) => x.right <= areaRight).filter(oneRectPerLine);
    let widows = rects.filter((x) => x.right > areaRight).filter(oneRectPerLine);
    return [orphans.length, widows.length];
}

const searchLineBreak = (current) => {
    if (current.start === 0) {
        return false;
    }
    let previous = current.copyShiftLeft();
    return current.getLeft() < previous.getLeft() ? current : searchLineBreak(previous);
}

const getPreviousLine = (textSection) => {
    if (!isText(textSection.node)) {
        return textSection;
    }
    let lineBreak = searchLineBreak(textSection);
    if (lineBreak !== false) {
        return lineBreak;
    }
    let previousSection = pipe(textSection, getNode, previousCousin, getLastChar);
    let currentSection = pipe(textSection, getNode, getfirstChar);
    return currentSection.getLeft < previousSection.getLeft ? currentSection : getPreviousLine(previousSection);
}

const handleWidows = (element, ratio) => {
    let textSection = ratio[1] > 1 ? pinpointOverflow(element) : pipe(element, pinpointOverflow, getPreviousLine);
    return isText(textSection.node) ? textSection.node.splitText(textSection.start) : textSection.node;
}

const divideElement = (element) => {
    let paragraph = isMerger(element) ? lastElementChild(element) : element;
    let ratio = orphansAndWidows(paragraph);
    return ratio[0] < 2 || (ratio[0] + ratio[1]) < 4 ? element : handleWidows(element, ratio);
}

// offcut creation

const prevLiCount = (element, acc = 0) => {
    if (!previousElementSibling(element)) {
        return acc;
    }
    let previous = previousElementSibling(element)
    if (isLi(previous)) {
        var acc = acc + 1;
    }
    return prevLiCount(previous, acc);
}

const cloneParent = (node) => {
    let parent = parentNode(node);
    let clone = cloneElement(parent);
    if (parent.nodeName === 'OL') {
        let itemNo = parent.start + prevLiCount(node);
        clone.setAttribute('start', itemNo);
    }
    return clone;  
}

const offcutCycle = (node, acc) => {
    let siblings = nextSibling(node) ? pipe(node, nextSibling, listRelatives(nextSibling)) : [];
    let clone = cloneParent(node);
    acc.appendChild(clone);
    let newChild = previousElementSibling(clone) ? previousElementSibling(clone) : node;
    appendTo(clone)(newChild);
    siblings.forEach((element) => {appendTo(clone)(element)});
    return acc;
}

const createOffcut = (node) => {
    let recursion = (node, acc = document.createDocumentFragment()) => {
        let parent = parentNode(node);
        return isTop(node) ? lastElementChild(acc) : recursion(parent, offcutCycle(node, acc));
    }    
    return isTop(node) ? node : recursion(node);
}

// high level pagination control

const pageBreak = (node) => {
    newPage();
    pipe(node,
        findOverflow,
        divideElement,
        createOffcut,
        addToPage,
        handleOverflow);
}

const handleOverflow = (node) => {
    if (detectOverflow(node)) {
        pageBreak(node);
    }
}

// execution 

const source = getSource();

const pages = pipe(createElement('div'), addClass('pages'), insertBefore(source[0]));
const style = pipe(createElement('style'), appendTo(head), append(styleContent()));
const template = pipe(createElement('template'), innerHTML(templateString));

const firstPage = createFirstPage();
const areaRight = pipe(firstPage, getPageContent, getRight) + safetyGap;

source.forEach((node) => pipe(node, setFlag('data-top'), addToPage, handleOverflow));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537