|
| 1 | +import { storeToRefs } from 'pinia'; |
| 2 | +import { useI18n } from 'vue-i18n'; |
| 3 | +import { Theme } from '@/styles/types'; |
| 4 | +import { DEFAULT_PRIMARY } from '@/config'; |
| 5 | +import { createDiscreteApi } from 'naive-ui'; |
| 6 | +import { asideTheme } from '@/styles/theme/aside.ts'; |
| 7 | +import { getLightColor, getDarkColor } from '@/utils'; |
| 8 | +import { useGlobalStore } from '@/stores/modules/global.ts'; |
| 9 | + |
| 10 | +/** |
| 11 | + * @description 全局主题 hooks |
| 12 | + * */ |
| 13 | + |
| 14 | +export const useTheme = () => { |
| 15 | + const globalStore = useGlobalStore(); |
| 16 | + |
| 17 | + const { t } = useI18n(); |
| 18 | + const { message } = createDiscreteApi(['message']); |
| 19 | + const { isDark, primary } = storeToRefs(globalStore); |
| 20 | + |
| 21 | + /** |
| 22 | + * @description 切换黑暗模式 同时修改主题颜色 |
| 23 | + */ |
| 24 | + const switchDark = (): void => { |
| 25 | + const html: HTMLElement = document.documentElement; |
| 26 | + |
| 27 | + if (isDark.value) { |
| 28 | + html.setAttribute('class', 'dark'); |
| 29 | + } else { |
| 30 | + html.setAttribute('class', ''); |
| 31 | + } |
| 32 | + |
| 33 | + changePrimary(primary.value); |
| 34 | + setAsideTheme(); |
| 35 | + }; |
| 36 | + |
| 37 | + /** |
| 38 | + * @description 切换主题颜色 |
| 39 | + */ |
| 40 | + const changePrimary = (val: string | null) => { |
| 41 | + if (!val) { |
| 42 | + val = DEFAULT_PRIMARY; |
| 43 | + message.success(`${t('Theme reset')} ${DEFAULT_PRIMARY}`); |
| 44 | + } |
| 45 | + |
| 46 | + // 计算主题颜色变化 |
| 47 | + document.documentElement.style.setProperty('--el-color-primary', val); |
| 48 | + document.documentElement.style.setProperty( |
| 49 | + '--el-color-primary-dark-2', |
| 50 | + isDark.value ? `${getLightColor(val, 0.2)}` : `${getDarkColor(val, 0.3)}` |
| 51 | + ); |
| 52 | + |
| 53 | + for (let i = 1; i <= 9; i++) { |
| 54 | + const primaryColor = isDark.value |
| 55 | + ? `${getDarkColor(val, i / 10)}` |
| 56 | + : `${getLightColor(val, i / 10)}`; |
| 57 | + document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, primaryColor); |
| 58 | + } |
| 59 | + |
| 60 | + globalStore.setGlobalState('primary', val); |
| 61 | + }; |
| 62 | + |
| 63 | + /** |
| 64 | + * @description 设置侧边样式 |
| 65 | + */ |
| 66 | + const setAsideTheme = () => { |
| 67 | + let type: Theme.ThemeType = 'light'; |
| 68 | + |
| 69 | + if (isDark.value) type = 'dark'; |
| 70 | + |
| 71 | + const theme = asideTheme[type!]; |
| 72 | + for (const [key, value] of Object.entries(theme)) { |
| 73 | + document.documentElement.style.setProperty(key, value); |
| 74 | + } |
| 75 | + }; |
| 76 | + |
| 77 | + /** |
| 78 | + * 初始化样式 |
| 79 | + */ |
| 80 | + const initTheme = () => { |
| 81 | + switchDark(); |
| 82 | + }; |
| 83 | + |
| 84 | + return { |
| 85 | + initTheme, |
| 86 | + switchDark, |
| 87 | + setAsideTheme, |
| 88 | + changePrimary |
| 89 | + }; |
| 90 | +}; |
0 commit comments