47 lines
1010 B
TypeScript
47 lines
1010 B
TypeScript
import type { AppThemeId } from '~/types/app-theme'
|
|
import { APP_THEME_OPTIONS } from '~/types/app-theme'
|
|
|
|
const STORAGE_KEY = 'policy-ui.theme.v1'
|
|
|
|
const VALID: AppThemeId[] = ['light', 'purple', 'dark', 'dark-purple']
|
|
|
|
function isThemeId(x: string): x is AppThemeId {
|
|
return (VALID as string[]).includes(x)
|
|
}
|
|
|
|
export function useAppTheme() {
|
|
const themeId = ref<AppThemeId>('light')
|
|
|
|
function applyTheme(id: AppThemeId) {
|
|
themeId.value = id
|
|
if (import.meta.client) {
|
|
document.documentElement.setAttribute('data-theme', id)
|
|
try {
|
|
localStorage.setItem(STORAGE_KEY, id)
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
}
|
|
|
|
onMounted(() => {
|
|
if (!import.meta.client) return
|
|
try {
|
|
const raw = localStorage.getItem(STORAGE_KEY)
|
|
if (raw && isThemeId(raw)) {
|
|
applyTheme(raw)
|
|
return
|
|
}
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
applyTheme('light')
|
|
})
|
|
|
|
return {
|
|
themeId,
|
|
themeOptions: APP_THEME_OPTIONS,
|
|
applyTheme
|
|
}
|
|
}
|