-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathscript.js
More file actions
67 lines (58 loc) · 2.08 KB
/
Copy pathscript.js
File metadata and controls
67 lines (58 loc) · 2.08 KB
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
/*
Short cuts for document querySelector and querySelectorAll
which can handle being used as template tags $`main` or $$`div`
Also if the first character is < then create a fragment instead
*/
const $ = (...s) => {
const str = Array.isArray(s[0]) ? String.raw(...s) : s[0];
return str[0] === '<' ? document.createRange().createContextualFragment(str) : document.querySelector(str);
}
const $$ = (...s) => {
const str = Array.isArray(s[0]) ? String.raw(...s) : s[0];
return Array.from(str[0] === '<' ? $(str).children : document.querySelectorAll(str));
}
/* Function for fetching a document fragment and replacing an element with it */
function replace(el,url) {
return fetch(url)
.then(r => r.text())
.then(html => {
el.parentNode.insertBefore($(html), el);
el.remove();
});
}
/* Update the window URL on swipe, this is throttled so that the history doesn't get filled with useless entries*/
function updateHistory(hash) {
clearTimeout(updateHistory.timeout);
updateHistory.timeout = setTimeout(function () {
if (window.location.hash !== hash) {
if (location.hash !== '') {
history.pushState({}, window.title, hash);
} else {
// On first page load update the URL in place
history.replaceState({}, window.title, hash);
}
}
}, 1000);
}
const iO = new IntersectionObserver(entries => entries.forEach(entry => {
const hash = '#'+entry.target.id;
const navEl = $`[href="${hash}"]`;
if (entry.isIntersecting && entry.intersectionRatio > 0.5) {
navEl.classList.add('focus');
updateHistory(hash);
} else {
navEl.classList.remove('focus');
}
}), {
root: $`main`,
threshold: 0.5
});
window.addEventListener('DOMContentLoaded', () => $$`article`.map(a => iO.observe(a)));
window.addEventListener('hashchange', function (e) {
const articleToShow = $(window.location.hash || '#' + $`article`.id);
articleToShow.scrollIntoView();
e.preventDefault();
}, false);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js');
}