useTheme.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) 2024 LangChat. TyCoding All Rights Reserved.
  3. *
  4. * Licensed under the GNU Affero General Public License, Version 3 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.gnu.org/licenses/agpl-3.0.html
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import type { GlobalThemeOverrides } from 'naive-ui';
  17. import { darkTheme, useOsTheme } from 'naive-ui';
  18. import { computed, watch } from 'vue';
  19. import { useAppStore } from '@/store';
  20. export function useTheme() {
  21. const appStore = useAppStore();
  22. const OsTheme = useOsTheme();
  23. const isDark = computed(() => {
  24. if (appStore.theme === 'auto') return OsTheme.value === 'dark';
  25. else return appStore.theme === 'dark';
  26. });
  27. const theme = computed(() => {
  28. return isDark.value ? darkTheme : undefined;
  29. });
  30. const themeOverrides = computed<GlobalThemeOverrides>(() => {
  31. if (isDark.value) {
  32. return {
  33. common: {},
  34. };
  35. }
  36. return {};
  37. });
  38. watch(
  39. () => isDark.value,
  40. (dark) => {
  41. if (dark) document.documentElement.classList.add('dark');
  42. else document.documentElement.classList.remove('dark');
  43. },
  44. { immediate: true }
  45. );
  46. return { theme, themeOverrides };
  47. }