dark.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { setCssVar } from './util';
  2. import { addClass, hasClass, removeClass } from '/@/utils/domUtils';
  3. export type CustomColorType = {
  4. name: string;
  5. light: string;
  6. dark: string;
  7. };
  8. /**
  9. * 自定义颜色列表
  10. * 需先在 src/design/color.less 内定义变量和 light 颜色
  11. */
  12. export const customColorList: CustomColorType[] = [
  13. {
  14. name: '--text-color',
  15. light: 'rgb(0,0,0,85%)',
  16. dark: '#c9d1d9',
  17. },
  18. {
  19. name: '--border-color',
  20. light: '#eee',
  21. dark: '#303030',
  22. },
  23. {
  24. name: '--component-background-color',
  25. light: '#fff',
  26. dark: '#151515',
  27. },
  28. {
  29. name: '--app-content-background-color',
  30. light: '#fafafa',
  31. dark: '#151515',
  32. },
  33. // custom example
  34. {
  35. name: '--custom-example-color',
  36. light: '#ff4d4f',
  37. dark: '#55D187',
  38. },
  39. ];
  40. // 根据主题更新自定义颜色
  41. export function updateCustomColor(mode: 'light' | 'dark') {
  42. customColorList.forEach((item) => {
  43. setCssVar(item.name, item[mode]);
  44. });
  45. }
  46. export async function updateDarkTheme(mode: string | null = 'light') {
  47. const htmlRoot = document.getElementById('htmlRoot');
  48. if (!htmlRoot) {
  49. return;
  50. }
  51. const hasDarkClass = hasClass(htmlRoot, 'dark');
  52. if (mode === 'dark') {
  53. htmlRoot.setAttribute('data-theme', 'dark');
  54. if (!hasDarkClass) {
  55. addClass(htmlRoot, 'dark');
  56. }
  57. } else {
  58. htmlRoot.setAttribute('data-theme', 'light');
  59. if (hasDarkClass) {
  60. removeClass(htmlRoot, 'dark');
  61. }
  62. }
  63. updateCustomColor(mode === 'dark' ? 'dark' : 'light');
  64. }