theme toggle with dark map style and mapterhorn terrain

This commit is contained in:
Vincent van der Wal
2026-07-22 11:26:26 +02:00
parent addef8b78e
commit bca5154459
5 changed files with 199 additions and 42 deletions
+37
View File
@@ -0,0 +1,37 @@
import { browser } from '$app/environment';
export type ThemePref = 'auto' | 'light' | 'dark';
let pref = $state<ThemePref>('auto');
let systemDark = $state(false);
if (browser) {
const stored = localStorage.getItem('theme');
if (stored === 'light' || stored === 'dark') pref = stored;
const mq = window.matchMedia('(prefers-color-scheme: dark)');
systemDark = mq.matches;
mq.addEventListener('change', (e) => (systemDark = e.matches));
}
function apply() {
if (!browser) return;
if (pref === 'auto') delete document.documentElement.dataset.theme;
else document.documentElement.dataset.theme = pref;
}
apply();
export const theme = {
get pref(): ThemePref {
return pref;
},
/** the resolved mode, following the system when pref is "auto" */
get isDark(): boolean {
return pref === 'dark' || (pref === 'auto' && systemDark);
},
cycle(): void {
pref = pref === 'auto' ? 'light' : pref === 'light' ? 'dark' : 'auto';
if (pref === 'auto') localStorage.removeItem('theme');
else localStorage.setItem('theme', pref);
apply();
}
};