Files
narlblog/frontend/src/components/ThemeSwitcher.astro
2026-03-27 12:58:04 +01:00

42 lines
1.7 KiB
Plaintext

---
const { defaultTheme } = Astro.props;
---
<div class="relative inline-block text-left">
<select
id="user-theme-switcher"
class="appearance-none bg-surface0/50 text-text border border-surface1 rounded-lg px-3 py-1.5 text-xs focus:outline-none focus:border-mauve transition-all cursor-pointer hover:bg-surface0 pr-8 shadow-sm"
>
<option value="mocha">Mocha</option>
<option value="macchiato">Macchiato</option>
<option value="frappe">Frappe</option>
<option value="latte">Latte</option>
<option value="scaled-and-icy">Scaled and Icy</option>
</select>
<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-subtext0">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-9"/></svg>
</div>
</div>
<script is:inline define:vars={{ defaultTheme }}>
const initTheme = () => {
const switcher = document.getElementById('user-theme-switcher');
if (switcher) {
const savedTheme = localStorage.getItem('user-theme') || defaultTheme;
switcher.value = savedTheme;
document.documentElement.className = savedTheme;
switcher.addEventListener('change', (e) => {
const newTheme = e.target.value;
localStorage.setItem('user-theme', newTheme);
document.documentElement.className = newTheme;
});
}
};
// Initialize immediately
initTheme();
// Re-initialize after Astro view transitions or navigation
document.addEventListener('astro:after-swap', initTheme);
</script>