import type { ReactNode } from 'react'
import Welcome from '../App'
import { featureRoutes } from '../features'
export type FeatureRoute = {
path: string
label?: string
render: (params: Readonly<Record<string, string>>) => ReactNode
}
export function navigate(path: string): void {
if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\')) throw new Error('Use a local application path')
window.location.assign(path)
}
function match(template: string, pathname: string): Record<string, string> | undefined {
const pattern = template.split('/')
const parts = pathname.split('/')
if (pattern.length !== parts.length) return undefined
const params: Record<string, string> = {}
for (let i = 0; i < pattern.length; i++) {
if (pattern[i].startsWith(':')) {
try { params[pattern[i].slice(1)] = decodeURIComponent(parts[i]) } catch { return undefined }
} else if (pattern[i] !== parts[i]) return undefined
}
return params
}
/** Explicit routes and ordinary links keep this starter independent of a router package. */
export function AppRouter() {
const pathname = window.location.pathname.replace(/\/$/, '') || '/'
const selected = featureRoutes.map(route => ({ route, params: match(route.path, pathname) }))
.find(item => item.params !== undefined)
const content = selected ? selected.route.render(selected.params!)
: pathname === '/' ? <Welcome /> : <main className="feature"><h1>Page not found</h1><a href="/">Go home</a></main>
if (featureRoutes.length === 0) return content
return <div className="application-shell">
{<nav className="feature-nav" aria-label="Application">
<a href="/">Home</a>
{featureRoutes.filter(route => route.label).map(route => <a key={route.path} href={route.path}>{route.label}</a>)}
</nav>}
{content}
</div>
}