Files
2026-10-27 05:49:38 -05:00

306 lines
10 KiB
JavaScript

/*
router.js — single-page router with clean paths + hash fallback.
Modes (decided once at boot by the inline script in index.html, recomputed here if absent):
history /title/tv/1399 (host rewrites unknown paths to index.html or 404.html)
hash /#/title/tv/1399 (file://, /index.html, or a hash route present on load)
Views: every route lazily imports a module exporting
render(root: HTMLElement, params) → cleanup function | void | Promise<cleanup|void>
update?(params) → boolean (optional: handle a same-route change in place, e.g. ?q=)
params = { ...pathParams (strings), query: URLSearchParams, path, route: name, signal: AbortSignal }
The signal aborts when the user navigates away; cleanup is also called then.
Public API:
navigate(path, { replace }), href(path) → string for <a href>, back(fallbackPath),
current() → { path, name, params, query }, register(name, pattern, loader),
onChange(fn) → unsubscribe, start(outlet), mode, root
*/
import { h } from './util.js';
const boot = window.__BUGTV_ROUTER || (() => {
const meta = document.querySelector('meta[name="bug-tv-root"]');
let root = meta && meta.content && !/^@.*@$/.test(meta.content) ? meta.content : '/';
if (!root.endsWith('/')) root += '/';
const hash = location.protocol === 'file:' || /\.html?$/i.test(location.pathname) || /^#\//.test(location.hash);
return { mode: hash ? 'hash' : 'history', root };
})();
export const mode = boot.mode;
export const root = boot.root;
const routes = [];
const listeners = new Set();
let outlet = null;
let active = null; // { route, mod, cleanup, controller, token }
let token = 0;
function compile(pattern) {
const keys = [];
const src = pattern
.replace(/\/+$/, '')
.split('/')
.map((seg) => {
if (!seg) return '';
const m = seg.match(/^:(\w+)(\?)?$/);
if (!m) return `/${seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`;
keys.push(m[1]);
return m[2] ? '(?:/([^/]+))?' : '/([^/]+)';
})
.join('');
return { re: new RegExp(`^${src || ''}/?$`), keys };
}
export function register(name, pattern, loader, defaults = {}) {
const { re, keys } = compile(pattern);
routes.push({ name, pattern, re, keys, loader, defaults });
}
// Built-in routes. The watch view is owned by the player workstream.
register('home', '/', () => import('./views/home.js'));
register('movies', '/movies', () => import('./views/home.js'), { kind: 'movie' });
register('tv', '/tv', () => import('./views/home.js'), { kind: 'tv' });
register('title', '/title/:type/:id', () => import('./views/title.js'));
register('watch', '/watch/:type/:id/:season?/:episode?', () => import('./views/watch.js'));
register('search', '/search', () => import('./views/search.js'));
register('list', '/list', () => import('./views/list.js'));
register('browse', '/browse/:type', () => import('./views/browse.js'));
register('settings', '/settings', () => import('./views/settings.js'));
function match(path) {
for (const r of routes) {
const m = r.re.exec(path);
if (!m) continue;
const params = { ...r.defaults };
r.keys.forEach((k, i) => {
if (m[i + 1] !== undefined) params[k] = decodeURIComponent(m[i + 1]);
});
return { route: r, params };
}
return null;
}
// Current app location → { path, search }
function location_() {
if (mode === 'hash') {
const raw = location.hash.replace(/^#/, '') || '/';
const i = raw.indexOf('?');
return { path: i >= 0 ? raw.slice(0, i) || '/' : raw, search: i >= 0 ? raw.slice(i) : '' };
}
let p = location.pathname;
if (p.startsWith(root)) p = `/${p.slice(root.length)}`;
else if (`${p}/` === root) p = '/';
return { path: p || '/', search: location.search };
}
export function href(path) {
const p = String(path || '/');
if (mode === 'hash') return `#${p.startsWith('/') ? p : `/${p}`}`;
return root + p.replace(/^\/+/, '');
}
export function current() {
const { path, search } = location_();
const m = match(path);
return { path, name: m ? m.route.name : null, params: m ? m.params : {}, query: new URLSearchParams(search) };
}
export function onChange(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
}
function saveScroll() {
try {
history.replaceState({ ...(history.state || {}), scrollY: window.scrollY }, '');
} catch (e) {
/* ignore */
}
}
export function navigate(path, opts = {}) {
const target = String(path || '/');
const cur = location_();
if (!opts.replace && target === cur.path + cur.search) return;
if (!opts.replace) {
saveScroll();
depth++;
}
if (mode === 'hash') {
const url = `${location.href.split('#')[0]}#${target}`;
if (opts.replace) history.replaceState({}, '', url);
else history.pushState({}, '', url);
} else {
const url = href(target);
if (opts.replace) history.replaceState({}, '', url);
else history.pushState({}, '', url);
}
resolve({ scroll: opts.replace ? 'keep' : 'top' });
}
let depth = 0; // in-app history entries we pushed (best effort)
export function back(fallback = '/') {
if (depth > 0) history.back();
else navigate(fallback, { replace: true });
}
function errorView(title, detail) {
return h('section.page.page--center',
h('div.empty',
h('div.empty__icon', '!'),
h('h1.empty__title', title),
detail ? h('p.empty__text', detail) : null,
h('a.btn.btn--primary', { href: href('/') }, 'Back to home')));
}
async function resolve({ scroll = 'top' } = {}) {
if (!outlet) return;
const loc = location_();
// legacy v4 URLs (watch.html?id=&type=&s=&e=, search.html?q=)
const legacy = legacyRedirect(loc);
if (legacy) {
navigate(legacy, { replace: true });
return;
}
const m = match(loc.path);
const query = new URLSearchParams(loc.search);
const my = ++token;
// same route + view supports in-place update (e.g. search ?q= typing)
if (m && active && active.route === m.route && active.mod && typeof active.mod.update === 'function') {
const handled = active.mod.update({ ...m.params, query, path: loc.path, route: m.route.name, signal: active.controller.signal });
if (handled) {
emit(m, loc);
return;
}
}
if (active) {
try {
active.controller.abort();
if (typeof active.cleanup === 'function') active.cleanup();
} catch (e) {
console.error(e);
}
active = null;
}
document.body.dataset.route = m ? m.route.name : 'notfound';
emit(m, loc);
outlet.replaceChildren();
outlet.setAttribute('aria-busy', 'true');
if (scroll !== 'keep') window.scrollTo(0, 0);
if (!m) {
outlet.replaceChildren(errorView('Page not found', 'That page does not exist.'));
outlet.removeAttribute('aria-busy');
return;
}
const controller = new AbortController();
const entry = { route: m.route, mod: null, cleanup: null, controller };
active = entry;
let mod;
try {
mod = await m.route.loader();
} catch (e) {
if (my !== token) return;
console.error(e);
outlet.replaceChildren(
errorView(
m.route.name === 'watch' ? 'Player unavailable' : 'Could not load this page',
m.route.name === 'watch' ? 'The player module is not installed yet.' : String(e && e.message ? e.message : e),
),
);
outlet.removeAttribute('aria-busy');
return;
}
if (my !== token) return;
entry.mod = mod;
const params = { ...m.params, query, path: loc.path, route: m.route.name, signal: controller.signal };
try {
if (typeof mod.render !== 'function') throw new Error('view has no render()');
const result = await mod.render(outlet, params);
if (my !== token || controller.signal.aborted) {
if (typeof result === 'function') result();
return;
}
entry.cleanup = result;
} catch (e) {
if (my !== token) return;
console.error(e);
outlet.replaceChildren(errorView('Something went wrong', String(e && e.message ? e.message : e)));
}
outlet.removeAttribute('aria-busy');
if (scroll === 'restore' && history.state && history.state.scrollY) {
const y = history.state.scrollY;
requestAnimationFrame(() => window.scrollTo(0, y));
setTimeout(() => window.scrollTo(0, y), 400);
}
}
function emit(m, loc) {
const info = { path: loc.path, name: m ? m.route.name : null, params: m ? m.params : {}, query: new URLSearchParams(loc.search) };
for (const fn of listeners) {
try {
fn(info);
} catch (e) {
console.error(e);
}
}
}
function legacyRedirect(loc) {
const p = loc.path.replace(/\/+$/, '');
if (/\/watch\.html$/.test(p)) {
const q = new URLSearchParams(loc.search);
const id = q.get('id');
const type = q.get('type') === 'tv' ? 'tv' : 'movie';
if (!id) return '/';
return type === 'tv' ? `/watch/tv/${id}/${q.get('s') || 1}/${q.get('e') || 1}` : `/watch/movie/${id}`;
}
if (/\/search\.html$/.test(p)) return `/search${loc.search}`;
if (/\/settings\.html$/.test(p)) return '/settings';
if (/\/(index|404)\.html$/.test(p) && mode === 'history') return `/${loc.search}`;
return null;
}
function onClick(e) {
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const a = e.target.closest && e.target.closest('a[href]');
if (!a || a.target === '_blank' || a.hasAttribute('download') || a.dataset.native != null) return;
const raw = a.getAttribute('href');
if (mode === 'hash') return; // "#/…" links navigate natively via hashchange
let url;
try {
url = new URL(a.href, location.href);
} catch (err) {
return;
}
if (url.origin !== location.origin || !url.pathname.startsWith(root) || raw.startsWith('#')) return;
if (/\.[a-z0-9]{2,5}$/i.test(url.pathname) && !/\/(index|404)\.html$/.test(url.pathname)) return;
e.preventDefault();
navigate(`/${url.pathname.slice(root.length)}${url.search}`);
}
export function start(el) {
outlet = el;
if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
document.addEventListener('click', onClick);
if (mode === 'hash') {
// covers <a href="#/…"> clicks and back/forward (pushState itself fires nothing)
window.addEventListener('hashchange', () => {
if (history.state && history.state.scrollY != null) depth = Math.max(0, depth - 1);
else depth++;
resolve({ scroll: 'restore' });
});
} else {
window.addEventListener('popstate', () => {
depth = Math.max(0, depth - 1);
resolve({ scroll: 'restore' });
});
}
resolve({ scroll: 'keep' });
}