MicProtocol / web /src /stores /theme.ts
Benard John
feat: implement full-stack architecture with database models, authentication services, and web dashboard components
37b5223
Raw History Blame Contribute Delete
1.08 kB
import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
export type Theme = 'light' | 'dark'
const STORAGE_KEY = 'ukweli_theme'
function getInitialTheme(): Theme {
if (typeof window === 'undefined') return 'light'
const stored = localStorage.getItem(STORAGE_KEY) as Theme | null
if (stored === 'light' || stored === 'dark') return stored
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
}
export const useThemeStore = defineStore('theme', () => {
const theme = ref<Theme>(getInitialTheme())
function apply(value: Theme) {
document.documentElement.setAttribute('data-theme', value)
// Naive UI needs the dark theme object
document.documentElement.classList.toggle('dark', value === 'dark')
localStorage.setItem(STORAGE_KEY, value)
}
function toggle() {
theme.value = theme.value === 'light' ? 'dark' : 'light'
}
function set(value: Theme) {
theme.value = value
}
// Apply on first load
apply(theme.value)
watch(theme, apply)
return { theme, toggle, set }
})