-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
70 lines (55 loc) · 2.14 KB
/
main.js
File metadata and controls
70 lines (55 loc) · 2.14 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
68
69
70
window.onload = async function () {
hookHistoryMethods();
window.addEventListener('locationchange', handleLocationChange);
const URLparts = window.location.pathname.split('/');
window.base = URLparts.length > 1 ? `/${URLparts[1]}/` : '/';
const response = await fetch(`${window.base}apps.json`);
window.apps = await response.json();
handleLocationChange();
document.addEventListener('click', (e) => {
const target = e.target;
if (target.matches('[data-route]')) {
const route = target.dataset.route;
if(route.includes(window.base)) window.history.pushState(null, '', route); // triggers locationchange
else window.location.assign(route);
e.preventDefault();
}
});
}
function hookHistoryMethods() {
const origPush = history.pushState;
const origReplace = history.replaceState;
history.pushState = function (...args) {
origPush.apply(this, args);
window.dispatchEvent(new Event('locationchange'));
};
history.replaceState = function (...args) {
origReplace.apply(this, args);
window.dispatchEvent(new Event('locationchange'));
};
window.addEventListener('popstate', () => {
window.dispatchEvent(new Event('locationchange'));
});
}
function handleLocationChange() {
const normalized = window.location.pathname.toLowerCase();
let path = normalized.endsWith('/') ? normalized : `${normalized}/`;
if(window.location.pathname !== path) {
window.history.replaceState(null, '', path);
}
renderContent();
}
async function renderContent() {
const URLroute = window.location.pathname.slice(window.base.length);
const route = URLroute.endsWith('/') ? URLroute.slice(0, -1) : URLroute;
let currentApp = window.apps[route] || '';
if (currentApp) {
document.getElementById('title').textContent = currentApp.title;
document.title = currentApp.title;
document.getElementById('app-link').dataset.route = currentApp.link;
}
else {
document.getElementById('title').textContent = 'Not Found';
document.title = 'Not Found';
}
}