Skip to content

Commit

Permalink
Merge pull request #1189 from tangly1024/feat/theme-switch
Browse files Browse the repository at this point in the history
Feat/theme switch
  • Loading branch information
tangly1024 committed Jun 23, 2023
2 parents 1e94107 + f6fea6a commit 1f8fc9a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
21 changes: 19 additions & 2 deletions lib/global.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function GlobalContextProvider({ children }) {
useEffect(() => {
initLocale(lang, locale, updateLang, updateLocale)
initDarkMode(isDarkMode, updateDarkMode)
initTheme()
if (isBrowser()) {
// 监听用户刷新页面
const handleBeforeUnload = (event) => {
Expand Down Expand Up @@ -55,10 +56,8 @@ export function GlobalContextProvider({ children }) {
NProgress.done()
setOnLoading(false)
}

const queryTheme = getQueryVariable('theme') || BLOG.THEME
setTheme(queryTheme)

router.events.on('routeChangeStart', handleStart)
router.events.on('routeChangeError', handleStop)
router.events.on('routeChangeComplete', handleStop)
Expand Down Expand Up @@ -98,4 +97,22 @@ export function GlobalContextProvider({ children }) {
)
}

/**
* 切换主题时的特殊处理
* @param {*} setTheme
*/
const initTheme = () => {
if (isBrowser()) {
setTimeout(() => {
const elements = document.querySelectorAll('[id^="theme-"]')
if (elements?.length > 1) {
elements[elements.length - 1].scrollIntoView()
// 删除前面的元素,只保留最后一个元素
elements[0].parentNode.removeChild(elements[0])
elements.pop()
}
}, 500)
}
}

export const useGlobal = () => useContext(GlobalContext)
10 changes: 1 addition & 9 deletions themes/theme.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import cookie from 'react-cookies'
import BLOG from '@/blog.config'
import { getQueryParam, getQueryVariable, isBrowser } from '../lib/utils'
import { getQueryParam, getQueryVariable } from '../lib/utils'
import dynamic from 'next/dynamic'
// 使用 __THEME__ 变量来动态导入主题组件
import * as ThemeComponents from '@theme-components'
Expand All @@ -21,14 +21,6 @@ export const getLayoutByTheme = (router) => {
const themeQuery = getQueryParam(router.asPath, 'theme') || BLOG.THEME
const layout = getLayoutNameByPath(router.pathname)
if (themeQuery !== BLOG.THEME) {
setTimeout(() => {
if (isBrowser()) {
const element = document?.getElementById('theme-' + themeQuery)
element?.scrollIntoView({
behavior: 'smooth'
})
}
}, 500)
return dynamic(() => import(`@/themes/${themeQuery}/${layout}`), { ssr: true })
} else {
return ThemeComponents[layout]
Expand Down

0 comments on commit 1f8fc9a

Please sign in to comment.