|
| 1 | +import type { AppConfig } from '@/store/types'; |
| 2 | + |
| 3 | +const body = document.documentElement as HTMLElement; |
| 4 | + |
| 5 | +// hex转rgb |
| 6 | +function hexToRgb(str: string) { |
| 7 | + const hxs: string[] = str.replace('#', '').match(/../g) || []; |
| 8 | + const newHxs: number[] = []; |
| 9 | + for (let i = 0; i < 3; i++) newHxs[i] = parseInt(hxs[i], 16); |
| 10 | + return newHxs; |
| 11 | +} |
| 12 | + |
| 13 | +// rgb转hex |
| 14 | +function rgbToHex(a: number, b: number, c: number) { |
| 15 | + const hexs = [a.toString(16), b.toString(16), c.toString(16)]; |
| 16 | + for (let i = 0; i < 3; i++) { |
| 17 | + if (hexs[i].length == 1) hexs[i] = `0${hexs[i]}`; |
| 18 | + } |
| 19 | + return `#${hexs.join('')}`; |
| 20 | +} |
| 21 | + |
| 22 | +// 参考element style 计算 |
| 23 | +function mix(color1: string, color2: string, weight: number) { |
| 24 | + weight = Math.max(Math.min(Number(weight), 1), 0); |
| 25 | + const mainColor = hexToRgb(color1); |
| 26 | + const mixColor = hexToRgb(color2); |
| 27 | + const hex = []; |
| 28 | + for (let i = 0; i < mainColor.length; i++) |
| 29 | + hex[i] = Math.round(mainColor[i] * (1 - weight) + mixColor[i] * weight); |
| 30 | + return rgbToHex(hex[0], hex[1], hex[2]); |
| 31 | +} |
| 32 | + |
| 33 | +export function updateColor(primaryColor: string, themeMode: 'light' | 'dark') { |
| 34 | + if (!primaryColor) return; |
| 35 | + |
| 36 | + const style = document.getElementById('admin-style-root-color'); |
| 37 | + |
| 38 | + const mixColor = themeMode === 'dark' ? '#141414' : '#ffffff'; |
| 39 | + let innerHTML = `html${ |
| 40 | + themeMode === 'dark' ? '.dark' : '' |
| 41 | + }:root{ --el-color-primary: ${primaryColor};\n`; |
| 42 | + |
| 43 | + // body.style.setProperty('--el-color-primary', primaryColor); |
| 44 | + for (let i = 1; i <= 9; i++) { |
| 45 | + // body.style.setProperty(`--el-color-primary-light-${i}`, mix(primaryColor, mixWhite, i * 0.1)); |
| 46 | + innerHTML += `--el-color-primary-light-${i}: ${mix(primaryColor, mixColor, i * 0.1)};\n`; |
| 47 | + } |
| 48 | + |
| 49 | + if (style) style.innerHTML = innerHTML + '}'; |
| 50 | +} |
| 51 | + |
| 52 | +export function themeHtmlClassName(className: string, isShow: boolean) { |
| 53 | + if (isShow) { |
| 54 | + body.classList.add(className); |
| 55 | + } else { |
| 56 | + body.classList.remove(className); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +export function configTheme(appConfig: AppConfig) { |
| 61 | + if (!appConfig) return; |
| 62 | + const { primaryColor, themeMode, colorWeaknessMode, greyMode } = appConfig; |
| 63 | + |
| 64 | + updateColor(primaryColor, themeMode); |
| 65 | + if (greyMode || colorWeaknessMode) { |
| 66 | + if (greyMode) themeHtmlClassName('html-grey', greyMode); |
| 67 | + else if (colorWeaknessMode) themeHtmlClassName('html-weakness', colorWeaknessMode); |
| 68 | + } |
| 69 | +} |
0 commit comments