fix: SvelteKit UI reactivity with Svelte 5 runes
* / replaces legacy $: syntax * Active menu highlight via .url.pathname (/stores) * Logout navigates to /login via goto() * Token/user footer updates reactively via
This commit is contained in:
parent
cc9da3ad7d
commit
78e53f42bf
@ -1,31 +1,40 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { browser } from '$app/environment';
|
|
||||||
import { page } from '$app/stores';
|
import { page } from '$app/stores';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
import '../app.css';
|
import '../app.css';
|
||||||
import { Toaster } from 'svelte-sonner';
|
import { Toaster } from 'svelte-sonner';
|
||||||
import { LogIn, LayoutDashboard, Phone, Cable, Users } from 'lucide-svelte';
|
import { LayoutDashboard, Phone, Cable, Users } from 'lucide-svelte';
|
||||||
|
|
||||||
let token: string | null = browser ? localStorage.getItem('token') : null;
|
let token: string | null = null;
|
||||||
let user: { username: string; role: string } | null = token
|
let user: { username: string; role: string } | null = null;
|
||||||
? (() => { try { return JSON.parse(atob(token.split('.')[1])); } catch { return null; } })()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
function logout() {
|
function updateAuth() {
|
||||||
if (browser) {
|
token = typeof localStorage !== 'undefined' ? localStorage.getItem('token') : null;
|
||||||
localStorage.removeItem('token');
|
if (token) {
|
||||||
localStorage.removeItem('refreshToken');
|
try { user = JSON.parse(atob(token.split('.')[1])); } catch { user = null; }
|
||||||
|
} else {
|
||||||
|
user = null;
|
||||||
}
|
}
|
||||||
token = null;
|
|
||||||
user = null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$: pathname = browser ? window.location.pathname : '';
|
function logout() {
|
||||||
$: isLogin = pathname === '/login';
|
localStorage.removeItem('token');
|
||||||
|
localStorage.removeItem('refreshToken');
|
||||||
|
updateAuth();
|
||||||
|
goto('/login');
|
||||||
|
}
|
||||||
|
|
||||||
|
let pathname = $derived($page.url.pathname);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
$page.url.pathname;
|
||||||
|
updateAuth();
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<Toaster position="top-right" />
|
<Toaster position="top-right" />
|
||||||
|
|
||||||
{#if !isLogin}
|
{#if pathname !== '/login'}
|
||||||
<div class="flex min-h-screen">
|
<div class="flex min-h-screen">
|
||||||
<!-- Sidebar -->
|
<!-- Sidebar -->
|
||||||
<aside class="w-64 border-r bg-card flex flex-col">
|
<aside class="w-64 border-r bg-card flex flex-col">
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user