2022-12-28 04:06:54 +03:00
|
|
|
import type { ColorMode } from '~/types'
|
|
|
|
import { InjectionKeyColorMode } from '~/constants/symbols'
|
2022-12-28 04:28:17 +03:00
|
|
|
import { COOKIE_KEY_COLOR_MODE, COOKIE_MAX_AGE } from '~/constants'
|
2022-12-28 04:06:54 +03:00
|
|
|
|
|
|
|
export default defineNuxtPlugin((nuxt) => {
|
2022-12-28 04:28:17 +03:00
|
|
|
const cookieColorMode = useCookie<ColorMode | null>(COOKIE_KEY_COLOR_MODE, { maxAge: COOKIE_MAX_AGE })
|
2022-12-28 04:06:54 +03:00
|
|
|
|
|
|
|
const preferColorMode = process.server ? computed(() => 'light') : usePreferredColorScheme()
|
|
|
|
const colorMode = computed<ColorMode>({
|
|
|
|
get() {
|
|
|
|
return cookieColorMode.value || preferColorMode.value as ColorMode
|
|
|
|
},
|
|
|
|
set(value) {
|
|
|
|
cookieColorMode.value = value
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
nuxt.vueApp.provide(InjectionKeyColorMode, colorMode)
|
|
|
|
|
|
|
|
if (process.server) {
|
|
|
|
useHead({
|
|
|
|
htmlAttrs: {
|
|
|
|
class: colorMode,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
watchEffect(() => {
|
|
|
|
document.documentElement.classList.toggle('dark', colorMode.value === 'dark')
|
|
|
|
document.documentElement.classList.toggle('light', colorMode.value === 'light')
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
useHead({
|
|
|
|
meta: [{
|
|
|
|
id: 'theme-color',
|
|
|
|
name: 'theme-color',
|
|
|
|
content: computed(() => colorMode.value === 'dark' ? '#111111' : '#ffffff'),
|
|
|
|
}],
|
|
|
|
})
|
|
|
|
})
|