封装theme,用cookie保存主题

This commit is contained in:
tangly1024
2022-03-22 12:38:47 +08:00
parent e98db24cb7
commit 09101daaab
4 changed files with 54 additions and 45 deletions

View File

@@ -2,7 +2,7 @@ import { generateLocaleDict, initLocale } from './lang'
import { createContext, useContext, useEffect, useState } from 'react'
import Router from 'next/router'
import BLOG from '@/blog.config'
import { ALL_THEME, initDarkMode } from '@/lib/theme'
import { ALL_THEME, initDarkMode, initTheme, saveThemeToCookies } from '@/lib/theme'
const GlobalContext = createContext()
let hasInit = false
@@ -26,6 +26,22 @@ export function GlobalContextProvider ({ children }) {
changeLoadingState(false)
})
function switchTheme () {
const currentIndex = ALL_THEME.indexOf(theme)
const newIndex = currentIndex < ALL_THEME.length - 1 ? currentIndex + 1 : 0
changeTheme(ALL_THEME[newIndex])
}
function changeTheme (theme) {
Router.query.theme = ''
if (ALL_THEME.indexOf(theme) > -1) {
setTheme(theme)
} else {
setTheme(BLOG.THEME)
}
saveThemeToCookies(theme)
}
useEffect(() => {
if (!hasInit) {
const userTheme = getQueryVariable('theme')
@@ -34,12 +50,13 @@ export function GlobalContextProvider ({ children }) {
}
initLocale(locale, updateLocale)
initDarkMode(isDarkMode, updateDarkMode)
initTheme(theme, changeTheme)
hasInit = true
}
})
return (
<GlobalContext.Provider value={{ onLoading, locale, updateLocale, isDarkMode, updateDarkMode, theme, setTheme }}>
<GlobalContext.Provider value={{ onLoading, locale, updateLocale, isDarkMode, updateDarkMode, theme, setTheme, switchTheme, changeTheme }}>
{children}
</GlobalContext.Provider>
)