From 2b58ff029107b23617d8c4b246de77876b3bf053 Mon Sep 17 00:00:00 2001
From: ivarlovlie <git@ivarlovlie.no>
Date: Wed, 28 Sep 2022 00:21:37 +0800
Subject: feat: Move frontend into layout group (main)

This enables /book to load without the usual layout (app layout)
---
 apps/kit/src/routes/(main)/+layout.svelte | 41 +++++++++++++++++++++++++++++++
 1 file changed, 41 insertions(+)
 create mode 100644 apps/kit/src/routes/(main)/+layout.svelte

(limited to 'apps/kit/src/routes/(main)/+layout.svelte')

diff --git a/apps/kit/src/routes/(main)/+layout.svelte b/apps/kit/src/routes/(main)/+layout.svelte
new file mode 100644
index 0000000..e5b177e
--- /dev/null
+++ b/apps/kit/src/routes/(main)/+layout.svelte
@@ -0,0 +1,41 @@
+<script lang="ts">
+    import "../../app.pcss";
+    import { afterNavigate, beforeNavigate, goto } from "$app/navigation";
+    import { is_active } from "$lib/session";
+    import type { Navigation } from "@sveltejs/kit";
+    import { setLocale } from "$lib/i18n/i18n-svelte";
+    import { onMount } from "svelte";
+    import type { LayoutData } from "./$types";
+    import LocaleSwitcher from "$lib/components/locale-switcher.svelte";
+
+    export let data: LayoutData;
+    onMount(() => setLocale(data.locale));
+
+    async function redirect_if_necessary(ticket: Navigation) {
+        const sessionIsValid = await is_active();
+        // TODO: ticket.to can be empty while navigating, so coalesce could probably cause non-public routes to cause a redir to /login...
+        const isPublicRoute =
+            (ticket.to?.routeId?.startsWith("(public)") ?? true) ||
+            ticket.to?.routeId?.startsWith("book");
+
+        console.log("redir: ", {
+            isPublicRoute,
+            sessionIsValid,
+        });
+
+        if (sessionIsValid && isPublicRoute) {
+            await goto("/home");
+        } else if (!sessionIsValid && !isPublicRoute) {
+            await goto("/login");
+        }
+    }
+
+    // This should probably be removed in favor of the logic in layout.server.ts.
+    // That requires a more sophisticated server side implementation of session handling,
+    // and i don't want that tbh, i want to stay as much in the browser as possible.
+    afterNavigate(redirect_if_necessary);
+    beforeNavigate(redirect_if_necessary);
+</script>
+
+<LocaleSwitcher />
+<slot />
-- 
cgit v1.3

