74 lines
2.3 KiB
JavaScript
74 lines
2.3 KiB
JavaScript
import { popup, addSheet } from '/static/util.js';
|
|
|
|
const content = document.getElementById('content');
|
|
let currentPathname = new URL(window.location).pathname;
|
|
let sheets = {};
|
|
|
|
async function loadContent(u, push=false) {
|
|
const sheet = window.document.styleSheets[0];
|
|
sheet.insertRule('.container { transition: max-width 1s; }', sheet.cssRules.length);
|
|
loadContent = _loadContent;
|
|
_loadContent(u, push);
|
|
}
|
|
async function _loadContent(u, push=false) {
|
|
let url = new URL(u);
|
|
if (url.pathname === currentPathname) {
|
|
return;
|
|
}
|
|
let p = url.pathname;
|
|
url.pathname = `_partial${url.pathname}`;
|
|
try {
|
|
const r = await fetch(url);
|
|
if (r.ok) {
|
|
let t = await r.text();
|
|
let metadata = JSON.parse(t.substring(4, t.indexOf('-->\n')))
|
|
let newSheets = metadata.sheets ?? [];
|
|
let loading = []
|
|
for (let s in sheets)
|
|
if (!newSheets.includes(s))
|
|
sheets[s].disabled = true;
|
|
for (let s of newSheets) {
|
|
if (!sheets[s])
|
|
loading.push(addSheet(s).then(e => sheets[s] = e));
|
|
else if (sheets[s].disabled)
|
|
sheets[s].disabled = false;
|
|
}
|
|
await Promise.all(loading);
|
|
content.innerHTML = t;
|
|
if (push)
|
|
history.pushState('', '', u);
|
|
content.querySelectorAll('script').forEach(e => {
|
|
let s = document.createElement('script');
|
|
Array.from(e.attributes).forEach(a => {
|
|
s.setAttribute(a.name, a.value)
|
|
})
|
|
s.appendChild(document.createTextNode(e.innerHTML));
|
|
e.parentNode.replaceChild(s, e);
|
|
});
|
|
document.title = metadata.title + ' - u.twoha.cc';
|
|
currentPathname = p;
|
|
} else {
|
|
popup(`${r.status} - ${r.statusText}`);
|
|
console.log(r)
|
|
}
|
|
} catch (e) {
|
|
popup(e);
|
|
}
|
|
}
|
|
window.addEventListener('popstate', e => {
|
|
let url = new URL(window.location);
|
|
loadContent(url);
|
|
});
|
|
document.body.addEventListener('click', e => {
|
|
if (e.target.localName === 'a') {
|
|
let url = new URL(e.target.href);
|
|
let current = new URL(window.location);
|
|
if (url.origin == current.origin) {
|
|
if (url.pathname === current.pathname && (url.hash || url.href.endsWith('#'))) return;
|
|
if (url.pathname.substring(url.pathname.lastIndexOf('/')).indexOf('.') !== -1) return;
|
|
e.preventDefault();
|
|
loadContent(url, true);
|
|
}
|
|
}
|
|
});
|