useTheme.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import {createGlobalState, useStorage} from "@vueuse/core";
  2. import mxConst from "../common/mxConst.js";
  3. import {genMixColor} from "../utils/gen-color.ts";
  4. import _ from 'lodash';
  5. export const defaultTheme = {
  6. // brands 里的颜色会自动生成多种变种,如 lighter、light、DEFAULT、deep、deeper
  7. brands: {
  8. primary: '#3a84f9',
  9. success: '#6ad000',
  10. warning: '#ff9800',
  11. error: '#f44336',
  12. info: '#999999'
  13. },
  14. // colors 里的颜色仅会生成 DEFAULT
  15. colors: {
  16. // 名称重复会覆盖brands自动生成色
  17. 'primary-deep': '#2b68f6',
  18. 'primary-light': '#4facfe',
  19. 'primary-lighter': '#48aef8',
  20. main: '#303133',
  21. content: '#606266',
  22. tips: '#909193',
  23. light: '#c0c4cc',
  24. border: '#dadbde',
  25. bg: '#f8fcff',
  26. disabled: '#c8c9cc'
  27. }
  28. }
  29. export const useTheme = createGlobalState(() => {
  30. // data
  31. const theme = useStorage(mxConst.keyTheme, defaultTheme)
  32. // methods
  33. const setTheme = (newTheme = {}) => {
  34. const mergedTheme = _.merge(defaultTheme, newTheme)
  35. theme.value = mergedTheme
  36. updateThemeColorVar(mergedTheme)
  37. }
  38. const setStyleProperty = (propName, value) => {
  39. document.documentElement.style.setProperty(propName, value);
  40. }
  41. const updateBrandExtendColorsVar = (color, name) => {
  42. // 生成混合色
  43. const {
  44. DEFAULT,
  45. dark,
  46. light
  47. } = genMixColor(color);
  48. // 每种主题色由浅到深分为五个阶梯以供开发者使用。
  49. setStyleProperty(`--${name}-lighter-color`, light[4]);
  50. setStyleProperty(`--${name}-light-color`, light[2]);
  51. setStyleProperty(`--${name}-color`, DEFAULT);
  52. setStyleProperty(`--${name}-deep-color`, dark[1]);
  53. setStyleProperty(`--${name}-deeper-color`, dark[3]);
  54. // elementPlus主题色更新 注释掉了暂时不使用的颜色定义
  55. // setStyleProperty(`--el-color-${name}`, DEFAULT);
  56. // setStyleProperty(`--el-color-${name}-dark-2`, dark[2]);
  57. // setStyleProperty(`--el-color-${name}-light-3`, light[3]);
  58. // setStyleProperty(`--el-color-${name}-light-5`, light[5]);
  59. // setStyleProperty(`--el-color-${name}-light-7`, light[7]);
  60. // setStyleProperty(`--el-color-${name}-light-8`, light[8]);
  61. setStyleProperty(`--el-color-${name}-light-9`, light[9]);
  62. }
  63. const updateThemeColorVar = ({brands, colors}) => {
  64. // 遍历当前主题色,生成混合色,并更新到css变量(tailwind + elementPlus)
  65. for (const [brand, color] of Object.entries(brands)) {
  66. updateBrandExtendColorsVar(color, brand)
  67. }
  68. for (const [name, color] of Object.entries(colors)) {
  69. setStyleProperty(`--${name}-color`, color);
  70. }
  71. }
  72. return {
  73. theme,
  74. setTheme
  75. }
  76. })