init
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import { readonly, shallowRef } from 'vue'
|
||||
|
||||
export const themes = [
|
||||
{ value: 'dcalc', label: 'DCalc 经典' },
|
||||
{ value: 'midnight', label: '深海蓝' },
|
||||
] as const
|
||||
|
||||
export type ThemeName = (typeof themes)[number]['value']
|
||||
|
||||
const THEME_STORAGE_KEY = 'dcalc-ui-theme'
|
||||
const activeTheme = shallowRef<ThemeName>('dcalc')
|
||||
let initialized = false
|
||||
|
||||
function isThemeName(value: string | null): value is ThemeName {
|
||||
return themes.some((theme) => theme.value === value)
|
||||
}
|
||||
|
||||
function applyTheme(theme: ThemeName) {
|
||||
activeTheme.value = theme
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.documentElement.dataset.theme = theme
|
||||
}
|
||||
}
|
||||
|
||||
export function initializeTheme() {
|
||||
if (initialized || typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
const storedTheme = window.localStorage.getItem(THEME_STORAGE_KEY)
|
||||
applyTheme(isThemeName(storedTheme) ? storedTheme : 'dcalc')
|
||||
initialized = true
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
initializeTheme()
|
||||
|
||||
function setTheme(theme: ThemeName) {
|
||||
applyTheme(theme)
|
||||
window.localStorage.setItem(THEME_STORAGE_KEY, theme)
|
||||
}
|
||||
|
||||
return {
|
||||
activeTheme: readonly(activeTheme),
|
||||
themes,
|
||||
setTheme,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user