u.twoha.cc/static/router.js
2024-09-13 19:49:18 -05:00

61 lines
1.9 KiB
JavaScript

import { popup } from '/static/util.js';
const content = document.getElementById('content');
let currentPathname = new URL(window.location).pathname;
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();
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);
});
let metadata = JSON.parse(document.querySelector('meta[name="metadata"]').content);
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);
}
}
});