Branchwell

Graphley / website / no-orphans.js

1/* No orphans: never leave one word alone on the last line of a paragraph, card or heading.
2 Joins the last two words of each block of text with a non-breaking space, on load and for text added later.
3 Pairs with no-orphans.css (text-wrap: pretty / balance). Public domain (CC0). */
4(function () {
5 if (window.__noOrphans) return;
6 window.__noOrphans = 1;
7 var SKIP = /^(SCRIPT|STYLE|PRE|CODE|TEXTAREA|INPUT|SELECT|OPTION|SVG|MATH|KBD|SAMP|NOSCRIPT|TEMPLATE|IFRAME|CANVAS|TITLE)$/;
8 var NB = ' ';
9 var WS = /[ \t\n\r]/;
10
11 function skipped(el) {
12 for (var n = el; n && n.nodeType === 1; n = n.parentNode) {
13 if (SKIP.test(n.nodeName.toUpperCase()) || n.isContentEditable || n.hasAttribute('data-orphans-ok')) return true;
14 }
15 return false;
16 }
17
18 // The box a run of text wraps inside: the nearest ancestor that is not an inline element.
19 function blockOf(node, cache) {
20 for (var el = node.parentNode; el && el.nodeType === 1; el = el.parentNode) {
21 var d = cache.get(el);
22 if (d === undefined) { d = getComputedStyle(el).display; cache.set(el, d); }
23 if (d !== 'inline' && d !== 'contents') return el;
24 }
25 return null;
26 }
27
28 function fix(block, nodes) {
29 var text = '';
30 for (var i = 0; i < nodes.length; i++) text += nodes[i].nodeValue;
31 var words = text.trim().split(/\s+/);
32 if (words.length < 3) return;
33 var last = words[words.length - 1], prev = words[words.length - 2];
34 if (last.indexOf(NB) >= 0 || last.length + prev.length > 30) return;
35 var seenWord = false;
36 for (i = nodes.length - 1; i >= 0; i--) {
37 var s = nodes[i].nodeValue;
38 for (var j = s.length - 1; j >= 0; j--) {
39 var c = s.charAt(j);
40 if (c === NB) { if (seenWord) return; continue; }
41 if (WS.test(c)) {
42 if (!seenWord) continue;
43 var k = j;
44 while (k > 0 && WS.test(s.charAt(k - 1))) k--;
45 var node = nodes[i], before = s;
46 node.nodeValue = s.slice(0, k) + NB + s.slice(j + 1);
47 // A long pair could push past a narrow box; put the space back if it does.
48 if (last.length + prev.length > 14) {
49 var de = document.documentElement;
50 if (block.scrollWidth > block.clientWidth + 1 || de.scrollWidth > de.clientWidth + 1) node.nodeValue = before;
51 }
52 return;
53 }
54 seenWord = true;
55 }
56 }
57 }
58
59 function run(root) {
60 if (!root || root.nodeType !== 1 || skipped(root)) return;
61 var cache = new Map(), blocks = [], groups = new Map();
62 var w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
63 acceptNode: function (t) { return t.nodeValue.trim() && !skipped(t.parentNode) ? 1 : 3; }
64 });
65 for (var t = w.nextNode(); t; t = w.nextNode()) {
66 var b = blockOf(t, cache);
67 if (!b) continue;
68 var g = groups.get(b);
69 if (!g) { g = []; groups.set(b, g); blocks.push(b); }
70 g.push(t);
71 }
72 for (var i = 0; i < blocks.length; i++) {
73 var blk = blocks[i];
74 // When only part of a block was handed in, read the whole block.
75 if (!root.contains(blk) || blk === root.parentNode) continue;
76 fix(blk, groups.get(blk));
77 }
78 }
79
80 var queued = [], timer = 0;
81 function flush() {
82 timer = 0;
83 var q = queued; queued = [];
84 var cache = new Map(), seen = new Set();
85 for (var i = 0; i < q.length; i++) {
86 var n = q[i];
87 if (!n || !n.isConnected) continue;
88 // Re-run from the text's own block so a new word at the end of a paragraph is handled.
89 var b = n.nodeType === 3 ? blockOf(n, cache) : (n.nodeType === 1 ? (getComputedStyle(n).display === 'inline' ? blockOf(n, cache) : n) : null);
90 if (b && !seen.has(b)) { seen.add(b); run(b); }
91 }
92 }
93 function start() {
94 run(document.body);
95 if (!window.MutationObserver) return;
96 new MutationObserver(function (muts) {
97 for (var i = 0; i < muts.length; i++) {
98 var m = muts[i];
99 if (m.type === 'characterData') queued.push(m.target);
100 for (var j = 0; j < m.addedNodes.length; j++) queued.push(m.addedNodes[j]);
101 }
102 if (queued.length && !timer) timer = setTimeout(flush, 60);
103 }).observe(document.body, { childList: true, subtree: true, characterData: true });
104 }
105 // Wait for the page (and any app framework) to finish its first render.
106 if (document.readyState === 'complete') setTimeout(start, 0);
107 else window.addEventListener('load', function () { setTimeout(start, 0); });
108})();