do frontend (preact)
This commit is contained in:
42
web/src/lib/state/theme.ts
Normal file
42
web/src/lib/state/theme.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user