forked from angryziber/kotlin-jooby-svelte-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.svelte
58 lines (49 loc) · 1.75 KB
/
App.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
<script lang="ts">
import router from './routing/Router'
import session, {user} from './auth/Session'
import gateway from '@ui/api/Gateway'
import type {User} from '@ui/api/types'
import LoginPage from './pages/LoginPage.svelte'
import NotFound from './pages/NotFound.svelte'
import AdminDashboardPage from './pages/admin/AdminDashboardPage.svelte'
import PageLayout from './layout/PageLayout.svelte'
import UserWelcomePage from './pages/user/UserWelcomePage.svelte'
import LoginLayout from './layout/LoginLayout.svelte'
import Toast from './shared/Toasts.svelte'
let page: string, pageParams = {}, isPublicPage = false
function onPageChanged() {
page = router.currentPage(location.pathname)
isPublicPage = page === 'login'
}
function matches(page: string, path: string) {
return pageParams = router.matches(path, page)
}
async function init() {
try {
session.user = await gateway.get('/api/user') as User
} catch (e) {
session.user = null
console.error(e)
}
onPageChanged()
window.addEventListener('popstate', onPageChanged)
if (!page && $user) router.navigateTo($user.role.toLowerCase(), {replaceHistory: true})
else if (!page || !$user && !isPublicPage) router.navigateTo('login', {replaceHistory: true})
else if (!isPublicPage && !page.startsWith($user?.role?.toLowerCase() ?? '')) page = ''
}
init()
</script>
<Toast/>
{#if page !== undefined}
<svelte:component this={isPublicPage ? LoginLayout : $user ? PageLayout : undefined}>
{#if matches(page, 'login')}
<LoginPage/>
{:else if matches(page, 'admin')}
<AdminDashboardPage/>
{:else if matches(page, 'user')}
<UserWelcomePage/>
{:else}
<NotFound/>
{/if}
</svelte:component>
{/if}