fix router
This commit is contained in:
1 parent
612baa461e
commit
594f6779e6
1 file changed
+15
-7
@@ -39,10 +39,22 @@ function createRouter() {
|
|||||||
let route = $state<Route>(parseHash(window.location.hash));
|
let route = $state<Route>(parseHash(window.location.hash));
|
||||||
|
|
||||||
// Sync from URL to state
|
// Sync from URL to state
|
||||||
|
$effect(() => {
|
||||||
const handleHashChange = () => {
|
const handleHashChange = () => {
|
||||||
route = parseHash(window.location.hash);
|
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);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Sync from state to URL
|
// Sync from state to URL
|
||||||
const navigate = (newRoute: Route) => {
|
const navigate = (newRoute: Route) => {
|
||||||
const newHash = routeToHash(newRoute);
|
const newHash = routeToHash(newRoute);
|
||||||
@@ -54,16 +66,12 @@ function createRouter() {
|
|||||||
route = newRoute;
|
route = newRoute;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Initialize and listen
|
|
||||||
if (typeof window !== 'undefined') {
|
|
||||||
window.addEventListener('hashchange', handleHashChange);
|
|
||||||
window.addEventListener('popstate', handleHashChange);
|
|
||||||
|
|
||||||
// Ensure initial URL is clean if empty
|
// Ensure initial URL is clean if empty
|
||||||
if (!window.location.hash && route.page !== 'overview') {
|
$effect(() => {
|
||||||
|
if (typeof window !== 'undefined' && !window.location.hash && route.page !== 'overview') {
|
||||||
navigate(route);
|
navigate(route);
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
get current() { return route; },
|
get current() { return route; },
|
||||||
|
|||||||
Reference in new issue
Block a user