router fix v2

This commit is contained in:
grove5_admin committed 2026-04-28 12:03:43 -07:00
1 parent 594f6779e6
commit ced4297e0d
2 files changed
+28 -33

No files matched your search

+21 -27
View File
@@ -1,3 +1,5 @@
import { writable, type Writable } from 'svelte/store';
export type Route =
| { page: 'overview' }
| { page: 'reference' }
@@ -35,25 +37,11 @@ function routeToHash(route: Route): string {
}
}
function createRouter() {
let route = $state<Route>(parseHash(window.location.hash));
function createRouter(route: Writable<Route>) {
// Sync from URL to state
$effect(() => {
const handleHashChange = () => {
route = parseHash(window.location.hash);
};
if (typeof window !== 'undefined') {
window.addEventListener('hashchange', handleHashChange);
window.addEventListener('popstate', handleHashChange);
return () => {
window.removeEventListener('hashchange', handleHashChange);
window.removeEventListener('popstate', handleHashChange);
};
}
});
const handleHashChange = () => {
route.set(parseHash(window.location.hash));
};
// Sync from state to URL
const navigate = (newRoute: Route) => {
@@ -63,21 +51,27 @@ function createRouter() {
if (newHash !== currentHash) {
window.history.pushState(null, '', newHash || window.location.pathname);
}
route = newRoute;
route.set(newRoute);
};
// Ensure initial URL is clean if empty
$effect(() => {
if (typeof window !== 'undefined' && !window.location.hash && route.page !== 'overview') {
navigate(route);
}
});
// Initialize and listen
if (typeof window !== 'undefined') {
window.addEventListener('hashchange', handleHashChange);
window.addEventListener('popstate', handleHashChange);
// Ensure initial URL is clean if empty
route.subscribe(initialRoute => {
if (!window.location.hash && initialRoute.page !== 'overview') {
navigate(initialRoute);
}
})();
}
return {
get current() { return route; },
navigate,
back: () => window.history.back(),
};
}
export const router = createRouter();
export const routeStore = writable<Route>(parseHash(window.location.hash));
export const router = createRouter(routeStore);