dark.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { darkCssIsReady, loadDarkThemeCss } from '@rys-fe/vite-plugin-theme/es/client';
  2. import { addClass, hasClass, removeClass } from '/@/utils/domUtils';
  3. export async function updateDarkTheme(mode: string | null = 'light') {
  4. const htmlRoot = document.getElementById('htmlRoot');
  5. if (!htmlRoot) {
  6. return;
  7. }
  8. const hasDarkClass = hasClass(htmlRoot, 'dark');
  9. if (mode === 'dark') {
  10. if (import.meta.env.PROD && !darkCssIsReady) {
  11. await loadDarkThemeCss();
  12. }
  13. htmlRoot.setAttribute('data-theme', 'dark');
  14. if (!hasDarkClass) {
  15. addClass(htmlRoot, 'dark');
  16. }
  17. } else if (mode === 'dark') {
  18. htmlRoot.setAttribute('data-theme', 'light');
  19. if (hasDarkClass) {
  20. removeClass(htmlRoot, 'dark');
  21. }
  22. } else {
  23. mode && htmlRoot.setAttribute('data-theme', mode);
  24. }
  25. }
  26. export async function updateAppTheme(mode: string = 'light', oldMode?: string) {
  27. const htmlRoot = document.getElementById('htmlRoot');
  28. if (!htmlRoot) {
  29. return;
  30. }
  31. const hasDarkClass = oldMode ? hasClass(htmlRoot, oldMode) : false;
  32. htmlRoot.setAttribute('data-theme', mode);
  33. if (oldMode && hasDarkClass) {
  34. removeClass(htmlRoot, oldMode);
  35. }
  36. }