Error pages: 404, 403, crash and server-rendered pages in the app's style

In the app: an unknown address shows a 404 inside the menu with the address, "Maybe you were looking for" suggestions (misspellings, partial names, moved pages) and a Ctrl+K search button; a page the role can't open shows a 403 "No access"; a render crash is caught by an error boundary (menu stays, clears on navigation, outer boundary for the sign-in and wall); missing servers, incidents and dead status links use the same page.

On the server: unknown /api, /auth, /agent and /metrics addresses and missing files now get a JSON 404 instead of the app's front page with a 200; browsers get self-contained 404, 500 and sign-in-failed pages in the sign-in card's look, light or dark, English or Swedish.

Swedish translations added. Tests in server/test/errorPages.test.ts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-17 18:06:14 +01:00
1 parent b8ce337dfb
commit 8ffae62281
16 files changed
+662 -31

No files matched your search

+9 -5
View File
@@ -1,6 +1,8 @@
import { Fragment, useEffect, useState, type ReactNode } from "react";
import { detectLanguage, forgetLanguage, setLanguage, t, useLanguage } from "./i18n";
import { Routes, Route, Navigate, useLocation, useParams } from "react-router-dom";
import { ErrorBoundary, ForbiddenPage } from "./components/ErrorPage";
import NotFound from "./pages/NotFound";
import { api, type CurrentUser, type UserRole, UnauthorizedError } from "./api/client";
import Login from "./pages/Login";
import Dashboard from "./pages/Dashboard";
@@ -96,11 +98,7 @@ function RequireRole({
minRole: UserRole;
children: ReactNode;
}) {
if (roleRank[user.role] < roleRank[minRole]) {
return (
<div className="alert alert-danger">{t("You don't have permission to view this page.")}</div>
);
}
if (roleRank[user.role] < roleRank[minRole]) return <ForbiddenPage minRole={minRole === "viewer" ? "operator" : minRole} />;
return <>{children}</>;
}
@@ -174,8 +172,10 @@ export default function App() {
}
function Shelled({ user }: { user: CurrentUser }) {
const { pathname } = useLocation();
return (
<AppShell user={user}>
<ErrorBoundary resetKey={pathname}>
<Routes>
<Route path="/" element={<Dashboard user={user} />} />
<Route path="/my-work" element={<MyWorkPage user={user} />} />
@@ -285,8 +285,12 @@ function Shelled({ user }: { user: CurrentUser }) {
<Route path="backup" element={<Navigate to="/settings/data" replace />} />
<Route path="logs" element={<Navigate to="/settings/data?view=logs" replace />} />
<Route path="cache" element={<Navigate to="/settings/data?view=cache" replace />} />
<Route path="*" element={<NotFound user={user} />} />
</Route>
{/* Anything else leads nowhere: say so, and offer the way on, rather than showing an empty page. */}
<Route path="*" element={<NotFound user={user} />} />
</Routes>
</ErrorBoundary>
<DialogHost />
<ToastHost />
</AppShell>
+136
View File
@@ -0,0 +1,136 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { Link } from "react-router-dom";
import { IconArrowLeft, IconLayoutDashboard, IconRefresh } from "@tabler/icons-react";
import { useEnvironment } from "../utils/environment";
import { t } from "../i18n";
/**
* A page that says where you ended up and what to do next, instead of a blank one: the code in large type, what it means, and the way out. Inside the app it sits where the page would
* have been, with the menu around it; "standalone" is for the places that have no menu (a link someone was given, a crash outside the app's frame) and gets a card with the logo, as the sign-in page has.
*/
export default function ErrorPage({ code, title, message, actions, children, standalone }: { code: string; title: string; message?: ReactNode; actions?: ReactNode; children?: ReactNode; standalone?: boolean }) {
const environment = useEnvironment();
const body = (
<div className="error-page">
<div className="error-code" aria-hidden="true">
{code}
</div>
<h2 className="page-title error-title">{title}</h2>
{message && <p className="error-message">{message}</p>}
{children}
{actions && <div className="error-actions">{actions}</div>}
</div>
);
if (!standalone) return body;
return (
<div className="login-screen">
<div className={`login-card error-card ${environment ? "login-card-env" : ""}`}>
<h1 className="login-logo">
<span className="logo-frame">
<img src="/logo.webp" alt="Homelab Manager" width={901} height={460} />
</span>
{environment?.name && <span className="badge env-badge">{environment.name}</span>}
</h1>
{body}
</div>
</div>
);
}
/** The way back to the start, which every error page offers. */
export function DashboardButton({ primary = true }: { primary?: boolean }) {
return (
<Link to="/" className={`btn ${primary ? "btn-primary" : ""}`}>
<IconLayoutDashboard size={18} className="me-1" aria-hidden="true" />
{t("Go to the dashboard")}
</Link>
);
}
/** For a page the person's role doesn't open. */
export function ForbiddenPage({ minRole }: { minRole: "operator" | "admin" }) {
return (
<ErrorPage
code="403"
title={t("No access")}
message={minRole === "admin" ? t("Only administrators can open this page.") : t("Only operators and administrators can open this page.")}
actions={<DashboardButton />}
/>
);
}
/** For one thing that isn't there (any more): a server, an incident — with the list it would have been in. */
export function MissingPage({ title, message, to, toLabel }: { title: string; message: ReactNode; to: string; toLabel: string }) {
return (
<ErrorPage
code="404"
title={title}
message={message}
actions={
<>
<Link to={to} className="btn btn-primary">
<IconArrowLeft size={18} className="me-1" aria-hidden="true" />
{toLabel}
</Link>
<DashboardButton primary={false} />
</>
}
/>
);
}
/** What a page that failed while it was being drawn shows. The details are for whoever has to find out why. */
function CrashPage({ error, standalone }: { error: Error; standalone?: boolean }) {
return (
<ErrorPage
code="500"
title={t("Something went wrong")}
message={t("This page ran into an error and couldn't be drawn. Reloading usually fixes it.")}
standalone={standalone}
actions={
<>
<button type="button" className="btn btn-primary" onClick={() => window.location.reload()}>
<IconRefresh size={18} className="me-1" aria-hidden="true" />
{t("Reload the page")}
</button>
{standalone ? (
<a className="btn" href="/">
{t("Go to the dashboard")}
</a>
) : (
<DashboardButton primary={false} />
)}
</>
}
>
<details className="error-details">
<summary>{t("Details for whoever looks into it")}</summary>
<pre>{error.message || String(error)}</pre>
</details>
</ErrorPage>
);
}
/**
* Catches a page that fails while it is drawn, so one page's bug leaves the menu and the rest of the app in place instead of a white screen. `resetKey` is the address: going to another
* page clears it.
*/
export class ErrorBoundary extends Component<{ children: ReactNode; resetKey?: string; standalone?: boolean }, { error: Error | null }> {
state: { error: Error | null } = { error: null };
static getDerivedStateFromError(error: Error) {
return { error };
}
componentDidCatch(error: Error, info: ErrorInfo) {
console.error(error, info.componentStack);
}
componentDidUpdate(prev: { resetKey?: string }) {
if (this.state.error && prev.resetKey !== this.props.resetKey) this.setState({ error: null });
}
render() {
return this.state.error ? <CrashPage error={this.state.error} standalone={this.props.standalone} /> : this.props.children;
}
}
+19
View File
@@ -239,6 +239,7 @@ export const sv: Record<string, string> = {
"All online": "Alla online",
"All reporting": "Alla rapporterar",
"All results": "Alla resultat",
"All servers": "Alla servrar",
"All severities": "Alla allvarlighetsgrader",
"All sources": "Alla källor",
"All statuses": "Alla status",
@@ -543,6 +544,7 @@ export const sv: Record<string, string> = {
"Description": "Beskrivning",
"Destination": "Mål",
"Details": "Detaljer",
"Details for whoever looks into it": "Detaljer för den som utreder det",
"Device": "Enhet",
"Device (optional)": "Enhet (valfri)",
"Devices": "Enheter",
@@ -752,7 +754,9 @@ export const sv: Record<string, string> = {
"Girls": "Flickor",
"Give it a new address": "Ge den en ny adress",
"Give up after": "Ge upp efter",
"Go back": "Gå tillbaka",
"Go to Servers": "Gå till Servrar",
"Go to the dashboard": "Gå till översikten",
"Go to the inventory": "Gå till inventariet",
"Good answers": "Bra svar",
"Got it": "Uppfattat",
@@ -849,6 +853,7 @@ export const sv: Record<string, string> = {
"In total": "Totalt",
"In your browser": "I din webbläsare",
"Inactive": "Inaktiv",
"Incident not found": "Incidenten hittades inte",
"Incidents": "Incidenter",
"Incidents began": "Incidenter som började",
"Indefinitely — automatic deletion is off.": "Obegränsat — automatisk borttagning är av.",
@@ -883,6 +888,7 @@ export const sv: Record<string, string> = {
"It is about the server": "Det gäller servern",
"It is not growing in a straight enough line to forecast.": "Den växer inte i en tillräckligt rak linje för att kunna förutsägas.",
"It is taken out of the incident's history.": "Den tas bort ur incidentens historik.",
"It may have ended or been taken back. Ask whoever gave it to you for a new one.": "Den kan ha upphört eller tagits tillbaka. Be den som gav dig den om en ny.",
"It relies on nothing here.": "Den förlitar sig inte på något här.",
"It runs on nothing, so its alerts always stand alone.": "Den körs inte på något, så dess larm står alltid på egna ben.",
"It runs on the server": "Det körs på servern",
@@ -1043,6 +1049,7 @@ export const sv: Record<string, string> = {
"Mark every new port as expected": "Markera varje ny port som förväntad",
"Matched to a server": "Kopplad till en server",
"Matching settings": "Matchande inställningar",
"Maybe you were looking for": "Du kanske letade efter",
"Measure again": "Mät igen",
"Measured on": "Uppmätt den",
"Media managers": "Mediahanterare",
@@ -1137,6 +1144,7 @@ export const sv: Record<string, string> = {
"Night": "Natt",
"Night — touch the screen to wake it": "Natt — rör vid skärmen för att väcka den",
"No": "Nej",
"No access": "Ingen åtkomst",
"No active alerts, but some checks couldn't run": "Inga aktiva larm, men vissa kontroller kunde inte köras",
"No active alerts.": "Inga aktiva larm.",
"No active sessions": "Inga aktiva sessioner",
@@ -1416,6 +1424,8 @@ export const sv: Record<string, string> = {
"One thing isn't working": "En sak fungerar inte",
"Online": "Online",
"Online / Total": "Online / Totalt",
"Only administrators can open this page.": "Bara administratörer kan öppna den här sidan.",
"Only operators and administrators can open this page.": "Bara operatörer och administratörer kan öppna den här sidan.",
"Only the first 200 are shown — search to find the others.": "Bara de första 200 visas — sök för att hitta de andra.",
"Only the larger ones": "Endast de större",
"Only those with updates": "Bara de med uppdateringar",
@@ -1451,6 +1461,7 @@ export const sv: Record<string, string> = {
"Package": "Paket",
"Page {page} of {pages} ({total} total)": "Sida {page} av {pages} ({total} totalt)",
"Page contains": "Sidan innehåller",
"Page not found": "Sidan hittades inte",
"Pages": "Sidor",
"Pages it shows, in the order of the board": "Sidor den visar, i tavlans ordning",
"Paid": "Betald",
@@ -1599,6 +1610,7 @@ export const sv: Record<string, string> = {
"Registrations": "Registreringar",
"Rejected": "Avvisade",
"Rejected in Semaphore": "Avvisad i Semaphore",
"Reload the page": "Ladda om sidan",
"Reminded daily from then until it's renewed.": "Påminns dagligen från då tills den förnyas.",
"Remote access": "Fjärråtkomst",
"Remove": "Ta bort",
@@ -1777,6 +1789,7 @@ export const sv: Record<string, string> = {
"Search servers…": "Sök servrar…",
"Search the change log": "Sök i ändringsloggen",
"Search the history": "Sök i historiken",
"Search the pages": "Sök bland sidorna",
"Search the title or the message": "Sök i rubriken eller meddelandet",
"Search users": "Sök användare",
"Search, or type a command": "Sök, eller skriv ett kommando",
@@ -1825,6 +1838,7 @@ export const sv: Record<string, string> = {
"Server": "Server",
"Server (optional)": "Server (valfri)",
"Server name": "Servernamn",
"Server not found": "Servern hittades inte",
"Server offline after": "Server offline efter",
"Server offline and disk-full alerts (for a server).": "Larm om offline-servrar och fulla diskar (för en server).",
"Server removed.": "Servern är borttagen.",
@@ -1929,6 +1943,7 @@ export const sv: Record<string, string> = {
"someone": "någon",
"Someone in none of those groups": "Någon i ingen av de grupperna",
"Something about to expire, an integration failing": "Något som håller på att gå ut, en integration som fallerar",
"Something went wrong": "Något gick fel",
"Sort A–Z": "Sortera A–Ö",
"Source": "Källa",
"Speed": "Hastighet",
@@ -2067,6 +2082,7 @@ export const sv: Record<string, string> = {
"The last backup didn't work": "Den senaste backupen fungerade inte",
"The last read is old, so this may be out of date.": "Den senaste avläsningen är gammal, så det här kan vara inaktuellt.",
"The latest backup didn't succeed, or the newest snapshot failed verification.": "Den senaste backupen lyckades inte, eller den senaste ögonblicksbilden klarade inte verifieringen.",
"The link may be old, or the page may have moved.": "Länken kan vara gammal, eller så har sidan flyttats.",
"The logo of the system for an integration’s page, the page’s own icon for the rest. Only for this browser, and it applies at once.": "Systemets logga för en integrations sida, sidans egen ikon för resten. Gäller bara den här webbläsaren och slår igenom direkt.",
"The maintenance window on {name} ends now. A playbook already started keeps running in Semaphore — it can't be stopped from here.": "Underhållsfönstret för {name} avslutas nu. En playbook som redan har startat fortsätter i Semaphore — den kan inte stoppas härifrån.",
"The metrics token": "Mätvärdestoken",
@@ -2093,7 +2109,9 @@ export const sv: Record<string, string> = {
"Theme": "Tema",
"There are no groups.": "Det finns inga grupper.",
"There are no options to edit on this kind of zone from here.": "Det finns inga alternativ att redigera för den här sortens zon härifrån.",
"There is no incident like that. It may be old enough to have been removed.": "Det finns ingen sådan incident. Den kan vara så gammal att den har tagits bort.",
"There is no osTicket integration yet. Add one under Integrations.": "Det finns ingen osTicket-integration ännu. Lägg till en under Integrationer.",
"There is no server with that number. It may have been removed.": "Det finns ingen server med det numret. Den kan ha tagits bort.",
"These need a certificate.": "Dessa behöver ett certifikat.",
"They could not be listed (the key may not be allowed to).": "De gick inte att lista (nyckeln kanske inte får).",
"They could not be listed.": "De gick inte att lista.",
@@ -2104,6 +2122,7 @@ export const sv: Record<string, string> = {
"This Homelab Manager instance uses a self-signed certificate (skip TLS verification on the agent)": "Den här Homelab Manager-instansen använder ett självsignerat certifikat (hoppa över TLS-verifiering i agenten)",
"This integration has no database login for closing tickets yet": "Den här integrationen har ingen databasinloggning för att stänga ärenden ännu",
"This link doesn't work any more": "Den här länken fungerar inte längre",
"This page ran into an error and couldn't be drawn. Reloading usually fixes it.": "Sidan stötte på ett fel och kunde inte visas. Det brukar räcka att ladda om den.",
"This plan has none.": "Den här planen har inga.",
"This preset has no TCP ports, and a scan only looks at TCP.": "Den här förinställningen har inga TCP-portar, och en skanning tittar bara på TCP.",
"This server has limits of its own; everything else follows Settings.": "Den här servern har egna gränser; allt annat följer Inställningar.",
+5 -1
View File
@@ -2,6 +2,7 @@ import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import { ErrorBoundary } from "./components/ErrorPage";
import "@tabler/core/dist/css/tabler.min.css";
import "./styles.css";
import { loadEnvironment } from "./utils/environment";
@@ -25,7 +26,10 @@ if ("serviceWorker" in navigator && import.meta.env.PROD) {
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<BrowserRouter>
<App />
{/* The last net: a crash outside the app's frame (the sign-in page, a wall display) still says what happened. */}
<ErrorBoundary standalone>
<App />
</ErrorBoundary>
</BrowserRouter>
</React.StrictMode>,
);
+2 -7
View File
@@ -7,6 +7,7 @@ import RunbookEntry from "../components/RunbookEntry";
import TimeAgo from "../components/TimeAgo";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
import { MissingPage } from "../components/ErrorPage";
import { confirmDialog } from "../utils/dialogs";
import { formatDateTime } from "../utils/date";
import { readableError } from "../utils/errors";
@@ -96,13 +97,7 @@ export default function IncidentDetail({ user }: { user: CurrentUser }) {
}
if (missing) {
return (
<div className="card">
<div className="card-body text-secondary">
There is no incident like that (it may be old enough to have been removed). <Link to="/alerts?view=history">{t("All incidents")}</Link>.
</div>
</div>
);
return <MissingPage title={t("Incident not found")} message={t("There is no incident like that. It may be old enough to have been removed.")} to="/alerts?view=history" toLabel={t("All incidents")} />;
}
if (!detail) {
return (
+54
View File
@@ -0,0 +1,54 @@
import { useMemo } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { IconArrowLeft, IconSearch } from "@tabler/icons-react";
import type { CurrentUser } from "../api/client";
import ErrorPage, { DashboardButton } from "../components/ErrorPage";
import { isGroup, visibleNav } from "../layout/nav";
import { suggestPages } from "../utils/pageSuggestions";
import { t } from "../i18n";
/** What an address that leads nowhere shows: the address, the pages of the menu it most looks like, and the ways on — the dashboard, back, and the search that opens with Ctrl+K. */
export default function NotFound({ user }: { user: CurrentUser }) {
const { pathname } = useLocation();
const navigate = useNavigate();
const suggestions = useMemo(() => {
const pages = visibleNav(user.role).flatMap((entry) => (isGroup(entry) ? entry.items : [entry])).map((leaf) => ({ to: leaf.to, label: t(leaf.label) }));
return suggestPages(pathname, pages);
}, [pathname, user.role]);
return (
<ErrorPage
code="404"
title={t("Page not found")}
message={t("The link may be old, or the page may have moved.")}
actions={
<>
<DashboardButton />
{window.history.length > 1 && (
<button type="button" className="btn" onClick={() => navigate(-1)}>
<IconArrowLeft size={18} className="me-1" aria-hidden="true" />
{t("Go back")}
</button>
)}
<button type="button" className="btn" onClick={() => window.dispatchEvent(new KeyboardEvent("keydown", { key: "k", ctrlKey: true, bubbles: true }))}>
<IconSearch size={18} className="me-1" aria-hidden="true" />
{t("Search the pages")}
</button>
</>
}
>
<code className="error-path">{pathname}</code>
{suggestions.length > 0 && (
<div className="error-suggest">
<div className="text-secondary small mb-2">{t("Maybe you were looking for")}</div>
<div className="d-flex gap-2 justify-content-center flex-wrap">
{suggestions.map((s) => (
<Link key={s.to} to={s.to} className="btn btn-sm btn-outline-primary">
{s.label}
</Link>
))}
</div>
</div>
)}
</ErrorPage>
);
}
+6 -1
View File
@@ -40,6 +40,7 @@ import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl";
import { confirmDialog } from "../utils/dialogs";
import { removeWithUndo } from "../utils/undoable";
import { ErrorNotice } from "../components/Notice";
import { MissingPage } from "../components/ErrorPage";
import { useBreadcrumbTail } from "../utils/breadcrumb";
import { PageSkeleton } from "../components/Skeleton";
import ViewTabs from "../components/ViewTabs";
@@ -405,7 +406,11 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
}
if (loading) return <PageSkeleton />;
if (error && !detail) return <div className="alert alert-danger">{error}</div>;
if (error && !detail) {
// A server number that isn't there (removed, or a mistyped address) is a missing page, not a failure to show in red.
if (/\(404\)/.test(error)) return <MissingPage title={t("Server not found")} message={t("There is no server with that number. It may have been removed.")} to="/servers" toLabel={t("All servers")} />;
return <div className="alert alert-danger">{error}</div>;
}
if (!detail) return null;
const { server, hardware, ipAddresses, dnsMatches, links } = detail;
+2 -6
View File
@@ -3,6 +3,7 @@ import { useParams } from "react-router-dom";
import { IconAlertTriangle, IconCircleCheck, IconHelpCircle, IconTool } from "@tabler/icons-react";
import { api, type PublicStatus, type PublicStatusItem } from "../api/client";
import { formatDateTime, setDateTimeSettings } from "../utils/date";
import ErrorPage from "../components/ErrorPage";
import { t } from "../i18n";
const REFRESH_MS = 30_000;
@@ -97,12 +98,7 @@ export default function SharedStatus() {
<div className="page-wrapper" style={{ minHeight: "100vh" }}>
<div className="container-tight py-4" style={{ maxWidth: 640, margin: "0 auto", paddingLeft: 16, paddingRight: 16 }}>
{state === "dead" ? (
<div className="card">
<div className="card-body text-center py-5">
<div className="h3 mb-1">{t("This link doesn't work any more")}</div>
<div className="text-secondary">It may have ended or been taken back. Ask whoever gave it to you for a new one.</div>
</div>
</div>
<ErrorPage code="404" title={t("This link doesn't work any more")} message={t("It may have ended or been taken back. Ask whoever gave it to you for a new one.")} />
) : !page ? (
<div className="text-center text-secondary py-5">{state === "unreachable" ? "Can't reach the server right now. Trying again…" : "Loading…"}</div>
) : (
+73
View File
@@ -2038,6 +2038,79 @@ tr.alert-row-child > td:first-child {
color: var(--tblr-secondary);
}
/* ── Error pages: 404, 403 and a page that failed. The code in large type, what it means, and the way out. ── */
.error-page {
max-width: 36rem;
margin: 0 auto;
padding: 3rem 1rem;
text-align: center;
}
.error-code {
font-size: clamp(4rem, 14vw, 7rem);
font-weight: 700;
line-height: 1;
letter-spacing: 0.02em;
color: var(--tblr-secondary);
opacity: 0.45;
}
.error-title {
display: block; /* Tabler lays .page-title out as a row, which would pull a short heading to the left */
margin: 0.75rem 0 0.25rem;
font-size: 1.5rem;
}
.error-message {
margin: 0 auto 1rem;
color: var(--tblr-secondary);
}
.error-path {
display: inline-block;
max-width: 100%;
margin-bottom: 1.25rem;
overflow-wrap: anywhere;
}
.error-suggest {
margin-bottom: 1.25rem;
}
.error-actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 0.5rem;
}
.error-details {
margin: 0 auto 1.25rem;
text-align: left;
font-size: 0.8125rem;
color: var(--tblr-secondary);
}
.error-details pre {
margin-top: 0.5rem;
max-height: 10rem;
overflow: auto;
white-space: pre-wrap;
}
/* On its own (a crash outside the app's frame): the card of the sign-in page, a little wider, with less space around. */
.error-card {
max-width: 30rem;
}
.error-card .error-page {
padding: 0.5rem 0 0;
}
.error-card .error-code {
font-size: clamp(3.5rem, 12vw, 5rem);
}
/* ── The dashboard's right-hand column: the to-do list as tall as the cards beside it (wide screens), a scrolling card of its own under them (narrow ones). ── */
.dash-side {
min-height: 24rem;
+52
View File
@@ -0,0 +1,52 @@
/**
* "Maybe you were looking for…": for an address that leads nowhere, the pages of the menu it most resembles — a misspelling (/sevrers), a part of one (/server, /alert), or a page that
* has moved under another (/settings/nothing → Settings). Pure, so it is tested without a screen.
*/
export interface PageRef {
label: string;
to: string;
}
const words = (text: string): string[] => text.toLowerCase().split(/[^a-z0-9åäö]+/).filter(Boolean);
/** How many single-letter changes (a letter added, dropped or changed, or two next to each other swapped) turn one word into the other. */
export function distance(a: string, b: string): number {
if (a === b) return 0;
const rows: number[][] = [Array.from({ length: b.length + 1 }, (_, j) => j)];
for (let i = 1; i <= a.length; i++) {
const row = [i];
for (let j = 1; j <= b.length; j++) {
row[j] = Math.min(rows[i - 1][j] + 1, row[j - 1] + 1, rows[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) row[j] = Math.min(row[j], rows[i - 2][j - 2] + 1);
}
rows.push(row);
}
return rows[a.length][b.length];
}
/** How well one typed word matches a word of a page: 3 the same, 2 the start of it (or a near miss), 0 not at all. */
function wordScore(typed: string, page: string): number {
if (typed === page) return 3;
if (typed.length >= 3 && page.startsWith(typed)) return 2;
if (page.length >= 3 && typed.startsWith(page)) return 2;
if (typed.length >= 4 && page.length >= 4 && distance(typed, page) <= (typed.length >= 9 ? 2 : 1)) return 2;
return 0;
}
/** The pages that look most like the address, best first; none when nothing does. */
export function suggestPages(pathname: string, pages: PageRef[], limit = 3): PageRef[] {
const typed = words(pathname.split(/[?#]/)[0]);
if (typed.length === 0) return [];
const seen = new Set<string>();
const scored: { page: PageRef; score: number }[] = [];
for (const page of pages) {
if (seen.has(page.to)) continue;
seen.add(page.to);
const mine = [...words(page.to), ...words(page.label)];
let score = 0;
for (const w of typed) score += Math.max(0, ...mine.map((p) => wordScore(w, p)));
if (score > 0) scored.push({ page, score });
}
scored.sort((a, b) => b.score - a.score || a.page.to.length - b.page.to.length);
return scored.slice(0, limit).map((s) => s.page);
}