32 lines
709 B
TypeScript
32 lines
709 B
TypeScript
import { ref, watch } from 'vue'
|
|
|
|
const STORAGE_KEY = 'mws_theme'
|
|
const DARK_CLASS = 'app-dark'
|
|
|
|
const isDark = ref(loadInitial())
|
|
|
|
function loadInitial(): boolean {
|
|
const stored = localStorage.getItem(STORAGE_KEY)
|
|
if (stored === 'dark') return true
|
|
if (stored === 'light') return false
|
|
return window.matchMedia('(prefers-color-scheme: dark)').matches
|
|
}
|
|
|
|
function apply(value: boolean) {
|
|
document.documentElement.classList.toggle(DARK_CLASS, value)
|
|
}
|
|
|
|
apply(isDark.value)
|
|
|
|
watch(isDark, (value) => {
|
|
apply(value)
|
|
localStorage.setItem(STORAGE_KEY, value ? 'dark' : 'light')
|
|
})
|
|
|
|
export function useTheme() {
|
|
function toggle() {
|
|
isDark.value = !isDark.value
|
|
}
|
|
return { isDark, toggle }
|
|
}
|