-
Notifications
You must be signed in to change notification settings - Fork 0
/
Router.svelte
45 lines (40 loc) · 1.16 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
<script context="module">
export function location() {
return window.location.hash.substring(1);
}
</script>
<script>
import { onMount } from 'svelte';
export let routes = {};
let currentComponent;
let params;
function hashChanged() {
let hash = document.location.hash.substring(1);
if (hash === "") {
hash = "/";
}
let comp = routes[hash];
if (!comp) {
for (let r in routes) {
let regex = "^" + r.replaceAll(":id", ".+") + "$";
if (hash.match(regex)) {
currentComponent = routes[r];
params = {id: hash.substring(hash.lastIndexOf("/")+1)};
return;
}
}
currentComponent = null;
params = null;
} else {
params = null;
currentComponent = comp;
}
}
onMount(() => hashChanged());
</script>
<svelte:window on:popstate={hashChanged} />
{#if currentComponent != null}
<svelte:component this={currentComponent} params={params} />
{:else}
<section><h1>Not found</h1><p>{location()}</p></section>
{/if}