40 lines
942 B
TypeScript
40 lines
942 B
TypeScript
import { createSignal } from 'solid-js'
|
|
|
|
export type ThemeMode = 'light' | 'dark'
|
|
|
|
const THEME_KEY = 'live-sfu-theme'
|
|
const [theme, setTheme] = createSignal<ThemeMode>('light')
|
|
|
|
function preferSystem(): ThemeMode {
|
|
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
|
}
|
|
|
|
function apply(mode: ThemeMode) {
|
|
const root = document.documentElement
|
|
root.classList.toggle('dark', mode === 'dark')
|
|
root.style.colorScheme = mode
|
|
try {
|
|
localStorage.setItem(THEME_KEY, mode)
|
|
} catch {
|
|
/* ignore private-mode storage errors */
|
|
}
|
|
setTheme(mode)
|
|
}
|
|
|
|
export function initTheme() {
|
|
let mode: ThemeMode = 'light'
|
|
try {
|
|
const saved = localStorage.getItem(THEME_KEY)
|
|
mode = saved === 'light' || saved === 'dark' ? saved : preferSystem()
|
|
} catch {
|
|
mode = preferSystem()
|
|
}
|
|
apply(mode)
|
|
}
|
|
|
|
export function toggleTheme() {
|
|
apply(theme() === 'dark' ? 'light' : 'dark')
|
|
}
|
|
|
|
export { theme }
|