const errorText = "EasyThemeConfig Error! " import {ThemeConfig} from "@/types/theme-config-types"; class EasyThemeConfig { private options: ThemeConfig[] = [] private currentTheme?: ThemeConfig private currentThemeIndex = 0 constructor(options: ThemeConfig[], currentThemeIndex = 0) { if (!options || options.length === 0) { throw new Error(`${errorText}config Error;you must be use Object`) } this.options = options this.validateConfigValues() this.currentThemeIndex = currentThemeIndex this.setCurrentThemeByIndex(this.currentThemeIndex) } setOptions(options: ThemeConfig[]) { this.options = options } getOptions() { return this.options } setCurrentTheme(theme: ThemeConfig) { return this.currentTheme } getCurrentTheme() { return this.currentTheme } setCurrentThemeIndex(index: number) { this.currentThemeIndex = index } getCurrentThemeIndex() { return this.currentThemeIndex } validateConfigValues() { const configList: any = this.options configList.forEach((config: any) => { if (!config || !config.theme || !config.config) { throw new Error(`${errorText}theme config has an error value!${JSON.stringify(config)}`) } }) } setCurrentThemeByIndex(index: number) { if (this.options.length <= index) { throw new Error(`${errorText}can not find the theme by this index!`) } this.currentTheme = this.options[index] this.currentThemeIndex = index this.setThemeForCSS() } setCurrentThemeByName(theme: string) { for (let i = 0; i < this.options.length; i++) { const config = this.options[i] if (config.theme === theme) { this.currentTheme = config this.currentThemeIndex = i this.setCurrentThemeIndex(i) this.setThemeForCSS() return } } } setThemeForCSS() { const themeConfig = this.currentTheme!.config const valueArr = Object.keys(themeConfig) for (let i = 0; i < valueArr.length; i++) { const key = valueArr[i] const value = themeConfig[key] document.documentElement.style.setProperty(key, value) } } } export default EasyThemeConfig export interface ThemeConfigType extends ThemeConfig{}