feat: implement theme persistence and selection in header component, enhancing user experience with localStorage integration

This commit is contained in:
2025-12-15 09:01:56 -03:00
parent 4faf279c3e
commit c272ca05e8
3 changed files with 87 additions and 3 deletions

View File

@@ -2,6 +2,8 @@
import { resolve } from '$app/paths';
import logo from '$lib/assets/logo_governo_PE.png';
import type { Snippet } from 'svelte';
import { onMount } from 'svelte';
import { aplicarTemaDaisyUI } from '$lib/utils/temas';
type HeaderProps = {
left?: Snippet;
@@ -9,6 +11,43 @@
};
const { left, right }: HeaderProps = $props();
let themeSelectEl: HTMLSelectElement | null = null;
function safeGetThemeLS(): string | null {
try {
const t = localStorage.getItem('theme');
return t && t.trim() ? t : null;
} catch {
return null;
}
}
onMount(() => {
const persisted = safeGetThemeLS();
if (persisted) {
// Sincroniza UI + HTML com o valor persistido (evita select ficar "aqua" indevido)
if (themeSelectEl && themeSelectEl.value !== persisted) {
themeSelectEl.value = persisted;
}
aplicarTemaDaisyUI(persisted);
}
});
function onThemeChange(e: Event) {
const nextValue = (e.currentTarget as HTMLSelectElement | null)?.value ?? null;
// Se o theme-change não atualizar (caso comum após login/logout),
// garantimos aqui a persistência + aplicação imediata.
if (nextValue) {
try {
localStorage.setItem('theme', nextValue);
} catch {
// ignore
}
aplicarTemaDaisyUI(nextValue);
}
}
</script>
<header
@@ -36,9 +75,11 @@
<div class="flex items-center gap-2">
<select
bind:this={themeSelectEl}
class="select select-sm bg-base-100 border-base-300 w-40"
aria-label="Selecionar tema"
data-choose-theme
onchange={onThemeChange}
>
<option value="aqua">Aqua</option>
<option value="sgse-blue">Azul</option>