// Tiny hash router - no dependency, matches the project's "no build step" // bias. Routes are registered with route(pattern, handler); handler gets // (root, params) where params come from ":name" segments in the pattern. const routes = []; export function route(pattern, handler) { const keys = []; const regexSource = pattern .split('/') .map((segment) => { if (segment.startsWith(':')) { keys.push(segment.slice(1)); return '([^/]+)'; } return segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }) .join('/'); routes.push({ regex: new RegExp('^' + regexSource + '$'), keys, handler }); } export function navigate(path) { location.hash = '#' + path; } export function start(root) { function render() { const path = (location.hash.slice(1) || '/').split('?')[0]; for (const r of routes) { const match = path.match(r.regex); if (match) { const params = {}; r.keys.forEach((key, i) => { params[key] = decodeURIComponent(match[i + 1]); }); root.innerHTML = ''; r.handler(root, params); return; } } root.innerHTML = '

Page introuvable.

'; } window.addEventListener('hashchange', render); render(); }