Files
Sybil-2/web/src/root-router.tsx
T

56 lines
2.0 KiB
TypeScript

import { useEffect, useState } from "preact/hooks";
import type { ComponentType } from "preact";
import { buildUiModeUrl, isLitePath } from "@/lib/ui-mode";
import { installLiteCompatibility } from "@/lib/lite-compat";
function routeName(path: string) {
return isLitePath(path) ? "lite" : path === "/search" ? "search" : "full";
}
async function loadPage(path: string) {
if (isLitePath(path)) {
installLiteCompatibility();
return import("@/pages/lite-route-page");
}
const [page] = await Promise.all([
path === "/search" ? import("@/pages/search-route-page") : import("@/App"),
import("./index.css"),
]);
return page;
}
export function RootRouter() {
const [Page, setPage] = useState<ComponentType | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let disposed = false;
const path = window.location.pathname;
void loadPage(path).then(page => {
if (!disposed) setPage(() => page.default);
}, () => {
if (!disposed) setFailed(true);
});
// Same-route history belongs to its page. Crossing presentations requires a
// clean document so the full UI's global CSS cannot leak into Lite.
const onPopState = () => {
if (routeName(window.location.pathname) !== routeName(path)) window.location.reload();
};
window.addEventListener("popstate", onPopState);
return () => {
disposed = true;
window.removeEventListener("popstate", onPopState);
};
}, []);
if (failed) {
return <main style={{ maxWidth: "36rem", margin: "2rem auto", padding: "1rem", fontFamily: "sans-serif" }}>
<h1>Sybil could not load</h1>
<p>Check your connection, then reload this page.</p>
<p><button onClick={() => window.location.reload()}>Reload</button></p>
<p><a href={buildUiModeUrl("lite")}>Lightweight UI</a> · <a href={buildUiModeUrl("full")}>Full UI</a></p>
</main>;
}
return Page ? <Page /> : <p role="status" style={{ margin: "2rem", fontFamily: "sans-serif" }}>Loading Sybil…</p>;
}