/*
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 = `
`
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));