dsec-notebook/src/lib/components/Navbar.svelte
2026-08-30 18:50:25 +08:00

92 lines
2.3 KiB
Svelte

<script lang="ts">
import { isAuthenticated, initAuth, logout } from "$lib/stores/auth";
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { page } from "$app/state";
let mobileMenuOpen = $state(false);
let auth = $state(false);
onMount(() => {
initAuth();
const unsub = isAuthenticated.subscribe((v) => (auth = v));
return () => unsub();
});
const path = $derived(page.url.pathname);
const onNotes = $derived(path === "/notes" || path.startsWith("/notes/"));
const onQuestions = $derived(path === "/questions" || path.startsWith("/questions/"));
</script>
<header class="border-rule border-b bg-white">
<div class="mx-auto flex h-16 max-w-4xl items-center justify-between px-4 sm:px-6">
<a href="/" class="text-ink font-serif text-[1.65rem] leading-none">Notebook</a>
<nav class="hidden items-center gap-8 md:flex">
<a href="/notes" class="nav-link {onNotes ? 'nav-link-active' : ''}">Notes</a>
<a href="/questions" class="nav-link {onQuestions ? 'nav-link-active' : ''}"
>Questions</a
>
{#if auth}
<button
type="button"
class="nav-link"
onclick={() => {
logout();
goto("/");
}}
>
Sign out
</button>
{:else}
<a href="/auth/login" class="nav-link">Sign in</a>
{/if}
</nav>
<button
class="text-muted hover:text-ink p-1 md:hidden"
aria-label="Open menu"
onclick={() => (mobileMenuOpen = !mobileMenuOpen)}
>
<svg
class="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="1.5"
>
<path stroke-linecap="square" d="M4 7h16M4 12h16M4 17h16" />
</svg>
</button>
</div>
{#if mobileMenuOpen}
<nav class="border-rule space-y-3 border-t px-4 py-4 md:hidden">
<a href="/notes" class="nav-link block" onclick={() => (mobileMenuOpen = false)}
>Notes</a
>
<a href="/questions" class="nav-link block" onclick={() => (mobileMenuOpen = false)}
>Questions</a
>
{#if auth}
<button
type="button"
class="nav-link block"
onclick={() => {
logout();
goto("/");
mobileMenuOpen = false;
}}
>
Sign out
</button>
{:else}
<a
href="/auth/login"
class="nav-link block"
onclick={() => (mobileMenuOpen = false)}>Sign in</a
>
{/if}
</nav>
{/if}
</header>