All files / src/stores theme.ts

94.44% Statements 17/18
70% Branches 7/10
100% Functions 5/5
94.44% Lines 17/18

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          2x 2x 2x   2x 17x     6x 6x 3x   3x   6x 6x           3x       3x     17x 3x 3x     17x    
import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
 
export type Theme = 'dark' | 'light'
 
const STORAGE_KEY = 'listme-theme'
const DARK_THEME_COLOR = '#303446'
const LIGHT_THEME_COLOR = '#eff1f5'
 
export const useThemeStore = defineStore('theme', () => {
  const theme = ref<Theme>((localStorage.getItem(STORAGE_KEY) as Theme) ?? 'dark')
 
  function applyTheme(t: Theme) {
    const html = document.documentElement
    if (t === 'light') {
      html.setAttribute('data-theme', 'latte')
    } else {
      html.removeAttribute('data-theme')
    }
    const metaThemeColor = document.querySelector('meta[name="theme-color"]')
    Iif (metaThemeColor) {
      metaThemeColor.setAttribute('content', t === 'light' ? LIGHT_THEME_COLOR : DARK_THEME_COLOR)
    }
  }
 
  function init() {
    applyTheme(theme.value)
  }
 
  function toggle() {
    theme.value = theme.value === 'dark' ? 'light' : 'dark'
  }
 
  watch(theme, (t) => {
    localStorage.setItem(STORAGE_KEY, t)
    applyTheme(t)
  })
 
  return { theme, init, toggle }
})