diff --git a/components/DarkModeButton.js b/components/DarkModeButton.js
index 9c3b046a..f1f8784d 100644
--- a/components/DarkModeButton.js
+++ b/components/DarkModeButton.js
@@ -1,5 +1,5 @@
import { useGlobal } from '@/lib/global'
-import { saveDarkModeToCookies } from '@/lib/theme'
+import { saveDarkModeToCookies } from '@/themes/theme'
const DarkModeButton = (props) => {
const { isDarkMode, updateDarkMode } = useGlobal()
diff --git a/components/DebugPanel.js b/components/DebugPanel.js
index 7765e827..4bbdbab9 100644
--- a/components/DebugPanel.js
+++ b/components/DebugPanel.js
@@ -2,7 +2,8 @@ import BLOG from '@/blog.config'
import { useEffect, useState } from 'react'
import Select from './Select'
import { useGlobal } from '@/lib/global'
-import { ALL_THEME } from '@/lib/theme'
+import { ALL_THEME } from '@/themes/theme'
+import { useRouter } from 'next/router'
/**
*
@@ -10,16 +11,14 @@ import { ALL_THEME } from '@/lib/theme'
*/
const DebugPanel = () => {
const [show, setShow] = useState(false)
- const { changeTheme, switchTheme, locale } = useGlobal()
+ const { theme, switchTheme, locale } = useGlobal()
+ const router = useRouter()
const [siteConfig, updateSiteConfig] = useState({})
- // const [themeConfig, updateThemeConfig] = useState({})
- const [debugTheme, updateDebugTheme] = useState(BLOG.THEME)
// 主题下拉框
const themeOptions = ALL_THEME.map(t => ({ value: t, text: t }))
useEffect(() => {
- changeTheme(BLOG.THEME)
updateSiteConfig(Object.assign({}, BLOG))
// updateThemeConfig(Object.assign({}, ThemeMap[BLOG.THEME].THEME_CONFIG))
}, [])
@@ -29,15 +28,13 @@ const DebugPanel = () => {
}
function handleChangeDebugTheme() {
- const newTheme = switchTheme()
- // updateThemeConfig(Object.assign({}, ThemeMap[newTheme].THEME_CONFIG))
- updateDebugTheme(newTheme)
+ switchTheme()
}
- function handleUpdateDebugTheme(e) {
- changeTheme(e)
- // updateThemeConfig(Object.assign({}, ThemeMap[theme].THEME_CONFIG))
- updateDebugTheme(e)
+ function handleUpdateDebugTheme(newTheme) {
+ console.log('切换主题', newTheme)
+ const query = { ...router.query, theme: newTheme }
+ router.push({ pathname: router.pathname, query })
}
function filterResult(text) {
@@ -75,7 +72,7 @@ const DebugPanel = () => {
diff --git a/components/ThemeSwitch.js b/components/ThemeSwitch.js
index d7143dc7..8fba9304 100644
--- a/components/ThemeSwitch.js
+++ b/components/ThemeSwitch.js
@@ -1,16 +1,23 @@
import { useGlobal } from '@/lib/global'
import React from 'react'
import { Draggable } from './Draggable'
-import { ALL_THEME } from '@/lib/theme'
+import { ALL_THEME } from '@/themes/theme'
+import { useRouter } from 'next/router'
/**
*
* @returns 主题切换
*/
const ThemeSwitch = () => {
- const { theme, changeTheme } = useGlobal()
+ const { theme } = useGlobal()
+ const router = useRouter()
+ // 修改当前路径url中的 theme 参数
+ // 例如 http://localhost?theme=hexo 跳转到 http://localhost?theme=newTheme
const onSelectChange = (e) => {
- changeTheme(e.target.value)
+ const newTheme = e.target.value
+ const query = router.query
+ query.theme = newTheme
+ router.push({ pathname: router.pathname, query })
}
return (<>
diff --git a/lib/global.js b/lib/global.js
index 3c2ecafc..d64853e4 100644
--- a/lib/global.js
+++ b/lib/global.js
@@ -1,11 +1,11 @@
import { generateLocaleDict, initLocale } from './lang'
import { createContext, useContext, useEffect, useState } from 'react'
-import Router, { useRouter } from 'next/router'
+import { useRouter } from 'next/router'
import BLOG from '@/blog.config'
-import { ALL_THEME, initDarkMode, initTheme, saveThemeToCookies } from '@/lib/theme'
+import { ALL_THEME, initDarkMode } from '@/themes/theme'
import NProgress from 'nprogress'
import LoadingCover from '@/components/LoadingCover'
-import { isBrowser } from './utils'
+import { getQueryVariable, isBrowser } from './utils'
const GlobalContext = createContext()
@@ -16,18 +16,17 @@ const GlobalContext = createContext()
* @constructor
*/
export function GlobalContextProvider({ children }) {
+ const router = useRouter()
const [lang, updateLang] = useState(BLOG.LANG) // 默认语言
const [locale, updateLocale] = useState(generateLocaleDict(BLOG.LANG)) // 默认语言
const [theme, setTheme] = useState(BLOG.THEME) // 默认博客主题
const [isDarkMode, updateDarkMode] = useState(BLOG.APPEARANCE === 'dark') // 默认深色模式
const [onLoading, setOnLoading] = useState(false) // 抓取文章数据
const [onReading, setOnReading] = useState(false) // 网页资源加载
- const router = useRouter()
useEffect(() => {
initLocale(lang, locale, updateLang, updateLocale)
initDarkMode(isDarkMode, updateDarkMode)
- initTheme(theme, changeTheme)
if (isBrowser()) {
// 监听用户刷新页面
const handleBeforeUnload = (event) => {
@@ -45,6 +44,11 @@ export function GlobalContextProvider({ children }) {
useEffect(() => {
const handleStart = (url) => {
NProgress.start()
+ const { theme } = router.query
+ if (theme && !url.includes(`theme=${theme}`)) {
+ const newUrl = `${url}${url.includes('?') ? '&' : '?'}theme=${theme}`
+ router.push(newUrl)
+ }
setOnLoading(true)
}
const handleStop = () => {
@@ -52,6 +56,9 @@ export function GlobalContextProvider({ children }) {
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)
@@ -62,24 +69,16 @@ export function GlobalContextProvider({ children }) {
}
}, [router])
+ // 切换主题
function switchTheme() {
const currentIndex = ALL_THEME.indexOf(theme)
const newIndex = currentIndex < ALL_THEME.length - 1 ? currentIndex + 1 : 0
const newTheme = ALL_THEME[newIndex]
- changeTheme(newTheme)
+ const query = { ...router.query, theme: newTheme }
+ router.push({ pathname: router.pathname, query })
return newTheme
}
- function changeTheme(theme) {
- Router.query.theme = ''
- if (ALL_THEME.indexOf(theme) > -1) {
- setTheme(theme)
- } else {
- setTheme(BLOG.THEME)
- }
- saveThemeToCookies(theme)
- }
-
return (
diff --git a/lib/notion/getNotionData.js b/lib/notion/getNotionData.js
index 8112b85e..977193b2 100644
--- a/lib/notion/getNotionData.js
+++ b/lib/notion/getNotionData.js
@@ -65,7 +65,7 @@ export async function getNotionPageData({ pageId, from }) {
const cacheKey = 'page_block_' + pageId
const data = await getDataFromCache(cacheKey)
if (data && data.pageIds?.length > 0) {
- console.log('[缓存]:', `from:${from}`, `root-page-id:${pageId}`, data)
+ console.log('[缓存]:', `from:${from}`, `root-page-id:${pageId}`)
return data
}
const pageRecordMap = await getDataBaseInfoByNotionAPI({ pageId, from })
diff --git a/lib/utils.js b/lib/utils.js
index df39fe64..d5ba09b5 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -51,16 +51,27 @@ export function loadExternalResource(url, type) {
* @param {}} variable
* @returns
*/
-export function getQueryVariable(variable) {
+export function getQueryVariable(key) {
const query = isBrowser() ? window.location.search.substring(1) : ''
const vars = query.split('&')
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split('=')
- if (pair[0] === variable) { return pair[1] }
+ if (pair[0] === key) { return pair[1] }
}
return (false)
}
+/**
+ * 获取 URL 中指定参数的值
+ * @param {string} url
+ * @param {string} param
+ * @returns {string|null}
+ */
+export function getQueryParam(url, param) {
+ const searchParams = new URLSearchParams(url.split('?')[1])
+ return searchParams.get(param)
+}
+
/**
* 深度合并两个对象
* @param target
diff --git a/next.config.js b/next.config.js
index c789c2d0..726eaae4 100644
--- a/next.config.js
+++ b/next.config.js
@@ -2,6 +2,9 @@ const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true'
})
+const { THEME } = require('./blog.config')
+const path = require('path')
+
module.exports = withBundleAnalyzer({
images: {
// 图片压缩
@@ -64,6 +67,10 @@ module.exports = withBundleAnalyzer({
// 'react-dom': 'preact/compat'
// })
// }
+
+ // 动态主题:添加 resolve.alias 配置,将动态路径映射到实际路径
+ config.resolve.alias['@theme-components'] = path.resolve(__dirname, 'themes', THEME)
+
return config
}
})
diff --git a/pages/404.js b/pages/404.js
index cb7ec336..2a521d7c 100644
--- a/pages/404.js
+++ b/pages/404.js
@@ -1,15 +1,7 @@
import { getGlobalNotionData } from '@/lib/notion/getNotionData'
import { useGlobal } from '@/lib/global'
-import dynamic from 'next/dynamic'
-import Loading from '@/components/Loading'
-import { Suspense, useEffect, useState } from 'react'
-import BLOG from '@/blog.config'
-
-const layout = 'Layout404'
-/**
- * 加载默认主题
- */
-const DefaultLayout = dynamic(() => import(`@/themes/${BLOG.THEME}/${layout}`), { ssr: true })
+import { useRouter } from 'next/router'
+import { getLayoutByTheme } from '@/themes/theme'
/**
* 404
@@ -17,22 +9,15 @@ const DefaultLayout = dynamic(() => import(`@/themes/${BLOG.THEME}/${layout}`),
* @returns
*/
const NoFound = props => {
- const { theme, siteInfo } = useGlobal()
+ const { siteInfo } = useGlobal()
const meta = { title: `${props?.siteInfo?.title} | 页面找不到啦`, image: siteInfo?.pageCover }
- const [Layout, setLayout] = useState(DefaultLayout)
- useEffect(() => {
- const loadLayout = async () => {
- const newLayout = await dynamic(() => import(`@/themes/${theme}/${layout}`))
- setLayout(newLayout)
- }
- loadLayout()
- }, [theme])
props = { ...props, meta }
- return }>
-
-
+ // 根据页面路径加载不同Layout文件
+ const Layout = getLayoutByTheme(useRouter())
+
+ return
}
export async function getStaticProps () {
diff --git a/pages/[...slug].js b/pages/[...slug].js
index 5363f73a..f28b0a42 100644
--- a/pages/[...slug].js
+++ b/pages/[...slug].js
@@ -1,23 +1,14 @@
import BLOG from '@/blog.config'
import { getPostBlocks } from '@/lib/notion'
import { getGlobalNotionData } from '@/lib/notion/getNotionData'
-import { useGlobal } from '@/lib/global'
-import { Suspense, useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
import { idToUuid } from 'notion-utils'
import { useRouter } from 'next/router'
import { isBrowser } from '@/lib/utils'
import { getNotion } from '@/lib/notion/getNotion'
import { getPageTableOfContents } from '@/lib/notion/getPageTableOfContents'
import md5 from 'js-md5'
-import dynamic from 'next/dynamic'
-import Loading from '@/components/Loading'
-
-const layout = 'LayoutSlug'
-
-/**
- * 懒加载默认主题
- */
-const DefaultLayout = dynamic(() => import(`@/themes/${BLOG.THEME}/${layout}`), { ssr: true })
+import { getLayoutByTheme } from '@/themes/theme'
/**
* 根据notion的slug访问页面
@@ -25,19 +16,11 @@ const DefaultLayout = dynamic(() => import(`@/themes/${BLOG.THEME}/${layout}`),
* @returns
*/
const Slug = props => {
- const { theme, setOnLoading } = useGlobal()
const { post, siteInfo } = props
const router = useRouter()
- const [Layout, setLayout] = useState(DefaultLayout)
- // 切换主题
- useEffect(() => {
- const loadLayout = async () => {
- const newLayout = await dynamic(() => import(`@/themes/${theme}/${layout}`))
- setLayout(newLayout)
- }
- loadLayout()
- }, [theme])
+ // 根据页面路径加载不同Layout文件
+ const Layout = getLayoutByTheme(useRouter())
// 文章锁🔐
const [lock, setLock] = useState(post?.password && post?.password !== '')
@@ -57,7 +40,6 @@ const Slug = props => {
// 文章加载
useEffect(() => {
- setOnLoading(false)
// 404
if (!post) {
setTimeout(() => {
@@ -98,9 +80,7 @@ const Slug = props => {
}
props = { ...props, lock, meta, setLock, validPassword }
- return }>
-
-
+ return
}
export async function getStaticPaths() {
diff --git a/pages/_app.js b/pages/_app.js
index 41fc3de3..9cee751f 100644
--- a/pages/_app.js
+++ b/pages/_app.js
@@ -33,9 +33,9 @@ const MyApp = ({ Component, pageProps }) => {
return (
-
-
-
+
+
+
)
}
diff --git a/pages/_document.js b/pages/_document.js
index d9e0b447..c053a632 100644
--- a/pages/_document.js
+++ b/pages/_document.js
@@ -2,7 +2,6 @@
import Document, { Html, Head, Main, NextScript } from 'next/document'
import BLOG from '@/blog.config'
import CommonScript from '@/components/CommonScript'
-import Loading from '@/components/Loading'
class MyDocument extends Document {
static async getInitialProps(ctx) {
@@ -22,7 +21,6 @@ class MyDocument extends Document {