43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
import { signal, effect } from '@preact/signals'
|
|
|
|
export type Theme = 'light' | 'dark' | 'auto'
|
|
const STORAGE_KEY = 'theme'
|
|
|
|
function getSavedTheme(): Theme | null {
|
|
const saved = localStorage.getItem(STORAGE_KEY)
|
|
if (saved == 'light' || saved == 'dark' || saved == 'auto') return saved
|
|
|
|
return null
|
|
}
|
|
|
|
export const theme = signal<Theme>(getSavedTheme() ?? 'auto')
|
|
document.body.setAttribute('data-theme', theme.value)
|
|
effect(() => {
|
|
const value = theme.value
|
|
localStorage.setItem(STORAGE_KEY, value)
|
|
document.body.setAttribute('data-theme', theme.value)
|
|
})
|
|
|
|
export function nextTheme(value: Theme): Theme {
|
|
switch (value) {
|
|
case 'light':
|
|
return 'auto'
|
|
case 'dark':
|
|
return 'light'
|
|
case 'auto':
|
|
return 'dark'
|
|
}
|
|
}
|
|
|
|
window.addEventListener('storage', event => {
|
|
if (event.key === STORAGE_KEY && event.newValue) {
|
|
if (
|
|
event.newValue === 'light' ||
|
|
event.newValue === 'dark' ||
|
|
event.newValue === 'auto'
|
|
) {
|
|
theme.value = event.newValue
|
|
}
|
|
}
|
|
})
|