themeUtil.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Copyright [2022] [https://www.xiaonuo.vip]
  3. * Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
  4. * 1.请不要删除和修改根目录下的LICENSE文件。
  5. * 2.请不要删除和修改Snowy源码头部的版权声明。
  6. * 3.本项目代码可免费商业使用,商业使用请保留源码和相关描述文件的项目出处,作者声明等。
  7. * 4.分发源码时候,请注明软件出处 https://www.xiaonuo.vip
  8. * 5.不可二次分发开源参与同类竞品,如有想法可联系团队xiaonuobase@qq.com商议合作。
  9. * 6.若您的项目无法满足以上几点,需要更多功能代码,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip
  10. */
  11. import { generate } from '@ant-design/colors'
  12. import tool from '../utils/tool'
  13. import config from '../config'
  14. import { themeEnum } from '@/layout/enum/themeEnum'
  15. const changeColor = (newPrimaryColor, theme, darkClass = 'snowy-theme-dark') => {
  16. return new Promise((resolve) => {
  17. const themeEleId = 'snowy-theme-var'
  18. const themeEle = document.querySelector(`#${themeEleId}`)
  19. if (themeEle && themeEle.parentNode) {
  20. themeEle.parentNode.removeChild(themeEle)
  21. }
  22. const isRealDark = theme === themeEnum.REAL_DARK
  23. if (newPrimaryColor) {
  24. const colors = generate(newPrimaryColor, isRealDark ? { theme: 'dark' } : {})
  25. const rootClass = isRealDark ? `.${darkClass}` : ':root'
  26. const styleElement = document.createElement('style')
  27. styleElement.id = themeEleId
  28. styleElement.setAttribute('type', 'text/css')
  29. styleElement.innerHTML = `${rootClass}{${colors
  30. .map((c, i) => {
  31. return `--primary-${i + 1}:${c};`
  32. })
  33. .concat([`--primary-color:${newPrimaryColor};`])
  34. .join('')}}`
  35. document.head.appendChild(styleElement)
  36. } else {
  37. document.body.removeAttribute('snowy-theme')
  38. }
  39. if (isRealDark) {
  40. document.body.classList.add(darkClass)
  41. } else {
  42. document.body.classList.remove(darkClass)
  43. }
  44. resolve()
  45. })
  46. }
  47. const loadLocalTheme = (localSetting) => {
  48. if (localSetting) {
  49. let { theme, themeColor } = localSetting
  50. themeColor = themeColor || config.COLOR
  51. theme = theme || config.THEME
  52. changeColor(themeColor, theme)
  53. }
  54. }
  55. /**
  56. * 获取本地保存的配置
  57. * @param loadTheme {boolean} 是否加载配置中的主题
  58. * @returns {Object}
  59. */
  60. const getLocalSetting = (loadTheme) => {
  61. let localSetting = {}
  62. try {
  63. const theme = tool.data.get('SNOWY_THEME')
  64. const themeColor = tool.data.get('SNOWY_THEME_COLOR')
  65. localSetting = {
  66. theme,
  67. themeColor
  68. }
  69. } catch (e) {
  70. console.error(e)
  71. }
  72. if (loadTheme) {
  73. loadLocalTheme(localSetting)
  74. }
  75. return localSetting
  76. }
  77. export { loadLocalTheme, getLocalSetting, changeColor }