theme.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import colors from 'css-color-function'
  2. const lightConfig = {
  3. 'dark-2': 'shade(20%)',
  4. 'light-3': 'tint(30%)',
  5. 'light-5': 'tint(50%)',
  6. 'light-7': 'tint(70%)',
  7. 'light-8': 'tint(80%)',
  8. 'light-9': 'tint(90%)'
  9. }
  10. const darkConfig = {
  11. 'light-3': 'shade(20%)',
  12. 'light-5': 'shade(30%)',
  13. 'light-7': 'shade(50%)',
  14. 'light-8': 'shade(60%)',
  15. 'light-9': 'shade(70%)',
  16. 'dark-2': 'tint(20%)'
  17. }
  18. const themeId = 'theme-vars'
  19. /**
  20. * @author Jason
  21. * @description 用于生成elementui主题的行为变量
  22. * 可选值有primary、success、warning、danger、error、info
  23. */
  24. export const generateVars = (color: string, type = 'primary', isDark = false) => {
  25. const colos = {
  26. [`--el-color-${type}`]: color
  27. }
  28. const config: Record<string, string> = isDark ? darkConfig : lightConfig
  29. for (const key in config) {
  30. colos[`--el-color-${type}-${key}`] = `color(${color} ${config[key]})`
  31. }
  32. return colos
  33. }
  34. /**
  35. * @author Jason
  36. * @description 用于设置css变量
  37. * @param key css变量key 如 --color-primary
  38. * @param value css变量值 如 #f40
  39. * @param dom dom元素
  40. */
  41. export const setCssVar = (key: string, value: string, dom = document.documentElement) => {
  42. dom.style.setProperty(key, value)
  43. }
  44. /**
  45. * @author Jason
  46. * @description 设置主题
  47. */
  48. export const setTheme = (options: Record<string, string>, isDark = false) => {
  49. const varsMap: Record<string, string> = Object.keys(options).reduce((prev, key) => {
  50. return Object.assign(prev, generateVars(options[key], key, isDark))
  51. }, {})
  52. let theme = Object.keys(varsMap).reduce((prev, key) => {
  53. const color = colors.convert(varsMap[key])
  54. return `${prev}${key}:${color};`
  55. }, '')
  56. theme = `:root{${theme}}`
  57. let style = document.getElementById(themeId)
  58. if (style) {
  59. style.innerHTML = theme
  60. return
  61. }
  62. style = document.createElement('style')
  63. style.setAttribute('type', 'text/css')
  64. style.setAttribute('id', themeId)
  65. style.innerHTML = theme
  66. document.head.append(style)
  67. }