syn/template/sources/core/router.js
GnomeZworc 6796e102e0
add template + document framework in root README
template/README.md: stripped to a one-liner bootstrap command.
README.md: full project docs (structure, add page, add component, build.sh).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-06-07 13:06:16 +02:00

41 lines
1.2 KiB
JavaScript

const response = await fetch('./pages.json')
if (!response.ok) throw new Error('router: failed to load pages.json — run build.sh')
const PAGES = await response.json()
const MODULE_CACHE = new Map()
let activeCSS = null
function currentRoute() {
const hash = window.location.hash.replace(/^#\//, '') || PAGES[0]?.route || ''
return hash.split('?')[0]
}
async function render(routeName) {
const page = PAGES.find(p => p.route === routeName) ?? PAGES[0]
const main = document.querySelector('main')
if (!main || !page) return
const htmlRes = await fetch(page.html)
if (!htmlRes.ok) throw new Error(`router: failed to load ${page.html}`)
main.innerHTML = await htmlRes.text()
activeCSS?.remove()
activeCSS = null
if (page.css) {
const link = document.createElement('link')
link.rel = 'stylesheet'
link.href = page.css
document.head.appendChild(link)
activeCSS = link
}
if (page.js) {
if (!MODULE_CACHE.has(page.js)) {
MODULE_CACHE.set(page.js, await import(`../${page.js}`))
}
MODULE_CACHE.get(page.js)?.init?.(main)
}
}
await render(currentRoute())
window.addEventListener('hashchange', () => render(currentRoute()))