2023-03-28 14:16:17 +08:00
|
|
|
import { ref, watchEffect } from "vue"
|
2022-10-17 15:04:27 +08:00
|
|
|
import { getActiveThemeName, setActiveThemeName } from "@/utils/cache/localStorage"
|
|
|
|
|
2023-02-28 14:12:38 +08:00
|
|
|
const DEFAULT_THEME_NAME = "normal"
|
|
|
|
type DefaultThemeNameType = typeof DEFAULT_THEME_NAME
|
|
|
|
|
|
|
|
/** 注册的主题名称, 其中 DefaultThemeNameType 是必填的 */
|
|
|
|
export type ThemeName = DefaultThemeNameType | "dark" | "dark-blue"
|
|
|
|
|
2022-10-17 15:04:27 +08:00
|
|
|
interface IThemeList {
|
|
|
|
title: string
|
|
|
|
name: ThemeName
|
|
|
|
}
|
|
|
|
|
2022-10-21 11:25:06 +08:00
|
|
|
/** 主题列表 */
|
|
|
|
const themeList: IThemeList[] = [
|
|
|
|
{
|
|
|
|
title: "默认",
|
2023-02-28 14:12:38 +08:00
|
|
|
name: DEFAULT_THEME_NAME
|
2022-10-21 11:25:06 +08:00
|
|
|
},
|
|
|
|
{
|
|
|
|
title: "黑暗",
|
|
|
|
name: "dark"
|
2022-10-21 18:06:56 +08:00
|
|
|
},
|
|
|
|
{
|
|
|
|
title: "深蓝",
|
|
|
|
name: "dark-blue"
|
2022-10-17 15:04:27 +08:00
|
|
|
}
|
2022-10-21 11:25:06 +08:00
|
|
|
]
|
2022-10-17 15:04:27 +08:00
|
|
|
|
2022-10-21 11:25:06 +08:00
|
|
|
/** 正在应用的主题名称 */
|
2023-02-28 14:12:38 +08:00
|
|
|
const activeThemeName = ref<ThemeName>(getActiveThemeName() || DEFAULT_THEME_NAME)
|
2022-10-17 15:04:27 +08:00
|
|
|
|
2022-10-21 11:25:06 +08:00
|
|
|
const setTheme = (value: ThemeName) => {
|
|
|
|
activeThemeName.value = value
|
|
|
|
}
|
|
|
|
|
|
|
|
/** 在 html 根元素上挂载 class */
|
|
|
|
const setHtmlClassName = (value: ThemeName) => {
|
|
|
|
document.documentElement.className = value
|
|
|
|
}
|
|
|
|
|
2023-03-28 17:48:39 +08:00
|
|
|
const initTheme = () => {
|
|
|
|
watchEffect(() => {
|
|
|
|
const value = activeThemeName.value
|
|
|
|
setHtmlClassName(value)
|
|
|
|
setActiveThemeName(value)
|
|
|
|
})
|
|
|
|
}
|
2023-03-28 14:16:17 +08:00
|
|
|
|
2022-10-21 11:25:06 +08:00
|
|
|
/** 主题 hook */
|
|
|
|
export function useTheme() {
|
2023-03-28 17:48:39 +08:00
|
|
|
return { themeList, activeThemeName, initTheme, setTheme }
|
2022-10-17 15:04:27 +08:00
|
|
|
}
|