All files / src/stores theme.store.ts

75% Statements 9/12
50% Branches 3/6
100% Functions 2/2
75% Lines 9/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49            3x   3x 3x 3x 3x   3x                                           3x 3x                   3x    
import { defineStore } from 'pinia';
import { ref, watch } from 'vue';
import { useTheme } from 'vuetify';
import { Theme } from '@3cr/viewer-types-ts';
import { useMediaQuery } from '@vueuse/core';
 
const THEME_KEY = 'theme';
 
export const useThemeStore = defineStore('theme', () => {
  const themeInstance = useTheme();
  const prefersLight = useMediaQuery('(prefers-color-scheme: light)');
  const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
 
  const theme = ref<Theme>(getLocalStorageTheme() ?? 'default');
 
  /* istanbul ignore next -- @preserve */
  watch(
    [theme, prefersLight, prefersDark],
    ([value]) => {
      theme.value = value;
      themeInstance.global.name.value =
        value !== 'default' ? value : getPreference();
      localStorage.setItem(THEME_KEY, value);
    },
    { immediate: true },
  );
 
  /* istanbul ignore next -- @preserve */
  function getLocalStorageTheme(): Theme | null {
    const value = localStorage.getItem(THEME_KEY);
    return value ? (value as Theme) : null;
  }
 
  /* v8 ignore start -- @preserve */
  function getPreference(): Theme {
    if (prefersLight.value) {
      return 'light';
    E} else if (prefersDark.value) {
      return 'dark';
    } else {
      // if no preference, default to light
      return 'light';
    }
  }
  /* v8 ignore stop -- @preserve */
 
  return { theme, prefersLight, prefersDark };
});