-
Notifications
You must be signed in to change notification settings - Fork 239
/
Copy pathRouter.svelte
72 lines (61 loc) · 1.83 KB
/
Router.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<script>
import { onMount, onDestroy, setContext } from "svelte";
import { writable } from "svelte/store";
import { createRouter } from "radix3";
export let routes = [];
const router = createRouter({
routes: routes.reduce((acc, route) => {
acc[route.path] = {
...route,
};
return acc;
}, {}),
});
const currentRoute = writable({ component: null });
function navigate(path, state) {
state = state || {};
const urlParsed = new URL(path, window.location.origin);
const routePayload = router.lookup(urlParsed.pathname);
if (routePayload) {
if (routePayload.component.toString().startsWith("class")) {
currentRoute.set(routePayload);
window.history.pushState(state, "", path);
} else if (typeof routePayload.component === "function") {
routePayload.component().then((module) => {
currentRoute.set({ ...routePayload, component: module.default });
window.history.pushState(state, "", path);
});
} else {
console.error("Invalid route component");
}
} else {
navigate("/");
}
}
window.onpopstate = () => {
navigate(window.location.href);
};
function handleClick(event) {
const target = event.target.closest("a[href]");
if (
target &&
target.getAttribute("href").startsWith("/") &&
target.getAttribute("target") !== "_blank"
) {
event.preventDefault();
navigate(target.getAttribute("href"));
}
}
onMount(() => {
document.addEventListener("click", handleClick);
navigate(window.location.href, { isInitialNavigation: true });
});
onDestroy(() => {
document.removeEventListener("click", handleClick);
});
setContext("router", {
currentRoute,
navigate,
});
</script>
<svelte:component this={$currentRoute.component} />