fix: rework setup to improve SSR compatibility

This commit is contained in:
Anthony Fu 2022-12-28 02:06:54 +01:00
parent fd7d30a38a
commit d8d163dbd0
22 changed files with 137 additions and 73 deletions

View file

@ -0,0 +1,41 @@
import type { ColorMode } from '~/types'
import { InjectionKeyColorMode } from '~/constants/symbols'
import { COOKIE_KEY_COLOR_MODE } from '~/constants'
export default defineNuxtPlugin((nuxt) => {
const cookieColorMode = useCookie<ColorMode | null>(COOKIE_KEY_COLOR_MODE, { default: () => null })
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'),
}],
})
})

View file

@ -0,0 +1,25 @@
import type { FontSize } from '~/types'
import { InjectionKeyFontSize } from '~/constants/symbols'
import { COOKIE_KEY_FONT_SIZE } from '~/constants'
import { fontSizeMap } from '~/constants/options'
export default defineNuxtPlugin((nuxt) => {
const DEFAULT = 'md'
const cookieFontSize = useCookie<FontSize>(COOKIE_KEY_FONT_SIZE, { default: () => DEFAULT })
nuxt.vueApp.provide(InjectionKeyFontSize, cookieFontSize)
if (!process.server) {
watchEffect(() => {
document.documentElement.style.setProperty('--font-size', fontSizeMap[cookieFontSize.value || DEFAULT])
})
}
else {
useHead({
style: [
{
innerHTML: `:root { --font-size: ${fontSizeMap[cookieFontSize.value || DEFAULT]}; }`,
},
],
})
}
})