Skip to content

Commit

Permalink
重构优化主题异步加载
Browse files Browse the repository at this point in the history
  • Loading branch information
tangly1024 committed Jun 7, 2023
1 parent 9247c4d commit 00d32c8
Show file tree
Hide file tree
Showing 107 changed files with 467 additions and 338 deletions.
7 changes: 4 additions & 3 deletions components/Live2D.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import { useEffect } from 'react'

export default function Live2D() {
const { theme, switchTheme } = useGlobal()
const showPet = JSON.parse(BLOG.WIDGET_PET)

useEffect(() => {
if (BLOG.WIDGET_PET) {
if (showPet) {
Promise.all([
loadExternalResource('https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/live2d.min.js', 'js')
]).then((e) => {
Expand All @@ -17,7 +18,7 @@ export default function Live2D() {
try {
loadlive2d('live2d', BLOG.WIDGET_PET_LINK)
} catch (error) {

console.error('读取PET模型', error)
}
}
})
Expand All @@ -30,7 +31,7 @@ export default function Live2D() {
}
}

if (!BLOG.WIDGET_PET || !JSON.parse(BLOG.WIDGET_PET)) {
if (!showPet) {
return <></>
}

Expand Down
23 changes: 12 additions & 11 deletions components/Loading.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import { useGlobal } from '@/lib/global'
import { useEffect } from 'react'

/**
* 主题文件被加载出之前的占位符
* @returns
*/
const Loading = (props) => {
const { theme, setOnReading } = useGlobal()
// const { theme, setOnReading } = useGlobal()
// console.log('开启遮罩')
// setOnReading(true)

useEffect(() => {
// 返回一个函数,在组件销毁时设置 onReading 为 false
return () => {
setTimeout(() => {
setOnReading(false)
}, 500)
}
}, [theme])
// useEffect(() => {
// // 返回一个函数,在组件销毁时设置 onReading 为 false
// return () => {
// setTimeout(() => {
// console.log('关闭遮罩')
// setOnReading(false)
// }, 500)
// }
// })

return <div className="w-screen h-screen flex justify-center items-center bg-black">
<i className='mr-5 fas fa-spinner animate-spin text-2xl' />
Expand Down
10 changes: 4 additions & 6 deletions components/LoadingCover.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@

/**
* 加载主题文件时的全局遮罩
* 加载文件时的全局遮罩
* @returns
*/
const LoadingCover = (props) => {
const { onReading } = props

return <>
<div className={`${onReading ? 'opacity-90' : 'opacity-0'} transition-all fixed top-0 left-0 pointer-events-none duration-1000 z-50 shadow-inner w-screen h-screen flex justify-center items-center bg-gray-600 dark:bg-black text-white shadow-text`}>
<h1 className="text-2xl"><i className='mr-5 fas fa-spinner animate-spin' /></h1>
</div>
</>
return <div className={`${onReading ? 'opacity-90' : 'opacity-0'} transition-all fixed top-0 left-0 pointer-events-none duration-1000 z-50 shadow-inner w-screen h-screen flex justify-center items-center bg-gray-400 dark:bg-black text-white shadow-text`}>
<i className='text-2xl mr-5 fas fa-spinner animate-spin' />
</div>
}
export default LoadingCover
2 changes: 2 additions & 0 deletions lib/global.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export function GlobalContextProvider({ children }) {
const handleBeforeUnload = (event) => {
setOnReading(true)
}
// 监听页面元素加载完
setOnReading(false)
window.addEventListener('beforeunload', handleBeforeUnload)
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload)
Expand Down
3 changes: 1 addition & 2 deletions pages/404.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { getGlobalNotionData } from '@/lib/notion/getNotionData'
import { useGlobal } from '@/lib/global'
import dynamic from 'next/dynamic'
import Loading from '@/components/Loading'

/**
* 404
Expand All @@ -11,7 +10,7 @@ import Loading from '@/components/Loading'
const NoFound = props => {
const { theme, siteInfo } = useGlobal()
const meta = { title: `${props?.siteInfo?.title} | 页面找不到啦`, image: siteInfo?.pageCover }
const Layout404 = dynamic(() => import(`@/themes/${theme}/Layout404`).then(async (m) => { return m.Layout404 }), { ssr: true, loading: () => <Loading /> })
const Layout404 = dynamic(() => import(`@/themes/${theme}/Layout404`))
return <Layout404 {...props} meta={meta}/>
}

Expand Down
61 changes: 36 additions & 25 deletions pages/[...slug].js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import BLOG from '@/blog.config'
import { getPostBlocks } from '@/lib/notion'
import { getGlobalNotionData } from '@/lib/notion/getNotionData'
import { useGlobal } from '@/lib/global'
import { useEffect, useState } from 'react'
import { Suspense, useEffect, useState } from 'react'
import { idToUuid } from 'notion-utils'
import { useRouter } from 'next/router'
import { isBrowser } from '@/lib/utils'
Expand All @@ -12,6 +12,11 @@ import md5 from 'js-md5'
import dynamic from 'next/dynamic'
import Loading from '@/components/Loading'

/**
* 懒加载默认主题
*/
const DefaultLayout = dynamic(() => import(`@/themes/${BLOG.THEME}/LayoutSlug`), { ssr: true })

/**
* 根据notion的slug访问页面
* @param {*} props
Expand All @@ -21,10 +26,18 @@ const Slug = props => {
const { theme, setOnLoading } = useGlobal()
const { post, siteInfo } = props
const router = useRouter()
const [Layout, setLayout] = useState(DefaultLayout)

// 切换主题
useEffect(() => {
const loadLayout = async () => {
setLayout(dynamic(() => import(`@/themes/${theme}/LayoutSlug`)))
}
loadLayout()
}, [theme])

// 文章锁🔐
const [lock, setLock] = useState(post?.password && post?.password !== '')
const LayoutSlug = dynamic(() => import(`@/themes/${theme}`).then(async (m) => { return m.LayoutSlug }), { ssr: true, loading: () => <Loading /> })

/**
* 验证文章密码
Expand All @@ -39,9 +52,24 @@ const Slug = props => {
return false
}

// 文章加载
useEffect(() => {
setOnLoading(false)
// 404
if (!post) {
setTimeout(() => {
if (isBrowser()) {
const article = document.getElementById('notion-article')
if (!article) {
router.push('/404').then(() => {
console.warn('找不到页面', router.asPath)
})
}
}
}, 8 * 1000) // 404时长 8秒
}

// 文章加密
if (post?.password && post?.password !== '') {
setLock(true)
} else {
Expand All @@ -56,37 +84,20 @@ const Slug = props => {
})
}, [post])

if (!post) {
setTimeout(() => {
if (isBrowser()) {
const article = document.getElementById('notion-article')
if (!article) {
router.push('/404').then(() => {
console.warn('找不到页面', router.asPath)
})
}
}
}, 8 * 1000) // 404时长 8秒
const meta = { title: `${props?.siteInfo?.title || BLOG.TITLE} | loading`, image: siteInfo?.pageCover || BLOG.HOME_BANNER_IMAGE }

return <LayoutSlug {...props} showArticleInfo={true} meta={meta} />
}

props = { ...props, lock, setLock, validPassword }

const meta = {
title: `${post?.title} | ${siteInfo?.title}`,
title: post ? `${post?.title} | ${siteInfo?.title}` : `${props?.siteInfo?.title || BLOG.TITLE} | loading`,
description: post?.summary,
type: post?.type,
slug: post?.slug,
image: post?.page_cover,
image: post?.page_cover || (siteInfo?.pageCover || BLOG.HOME_BANNER_IMAGE),
category: post?.category?.[0],
tags: post?.tags
}
props = { ...props, lock, meta, setLock, validPassword }

return (
<LayoutSlug {...props} showArticleInfo={true} meta={meta} />
)
return <Suspense fallback={<Loading />}>
<Layout {...props} />
</Suspense>
}

export async function getStaticPaths() {
Expand Down
26 changes: 22 additions & 4 deletions pages/archive/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
import { getGlobalNotionData } from '@/lib/notion/getNotionData'
import React from 'react'
import React, { Suspense, useEffect, useState } from 'react'
import { useGlobal } from '@/lib/global'
import dynamic from 'next/dynamic'
import BLOG from '@/blog.config'

import Loading from '@/components/Loading'

/**
* 加载默认主题
*/
const DefaultLayout = dynamic(() => import(`@/themes/${BLOG.THEME}/LayoutArchive`), { ssr: true })

const ArchiveIndex = props => {
const { theme, locale } = useGlobal()
const { siteInfo } = props
const { theme, locale } = useGlobal()
const [Layout, setLayout] = useState(DefaultLayout)
// 切换主题
useEffect(() => {
const loadLayout = async () => {
setLayout(dynamic(() => import(`@/themes/${theme}/LayoutArchive`)))
}
loadLayout()
}, [theme])

const meta = {
title: `${locale.NAV.ARCHIVE} | ${siteInfo?.title}`,
description: siteInfo?.description,
Expand All @@ -16,8 +31,11 @@ const ArchiveIndex = props => {
type: 'website'
}

const LayoutArchive = dynamic(() => import(`@/themes/${theme}`).then(async (m) => { return m.LayoutArchive }), { ssr: true, loading: () => <Loading /> })
return <LayoutArchive {...props} meta={meta} />
props = { ...props, meta }

return <Suspense fallback={<Loading/>}>
<Layout {...props} />
</Suspense>
}

export async function getStaticProps() {
Expand Down
33 changes: 23 additions & 10 deletions pages/category/[category]/index.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
import { getGlobalNotionData } from '@/lib/notion/getNotionData'
import React from 'react'
import React, { Suspense, useEffect, useState } from 'react'
import { useGlobal } from '@/lib/global'
import dynamic from 'next/dynamic'
import BLOG from '@/blog.config'

import Loading from '@/components/Loading'

/**
* 加载默认主题
*/
const DefaultLayout = dynamic(() => import(`@/themes/${BLOG.THEME}/LayoutCategory`), { ssr: true })

/**
* 分类页
* @param {*} props
* @returns
*/
export default function Category(props) {
const { theme } = useGlobal()
const { siteInfo, posts } = props
const { locale } = useGlobal()
if (!posts) {
const Layout404 = dynamic(() => import(`@/themes/${theme}`).then(async (m) => { return m.Layout404 }), { ssr: true, loading: () => <Loading /> })
return <Layout404 {...props} />
}
const { siteInfo } = props
const { locale, theme } = useGlobal()
const [Layout, setLayout] = useState(DefaultLayout)
// 切换主题
useEffect(() => {
const loadLayout = async () => {
setLayout(dynamic(() => import(`@/themes/${theme}/LayoutCategory`)))
}
loadLayout()
}, [theme])

const meta = {
title: `${props.category} | ${locale.COMMON.CATEGORY} | ${
siteInfo?.title || ''
Expand All @@ -28,8 +38,11 @@ export default function Category(props) {
type: 'website'
}

const LayoutCategory = dynamic(() => import(`@/themes/${theme}`).then(async (m) => { return m.LayoutCategory }), { ssr: true, loading: () => <Loading /> })
return <LayoutCategory {...props} meta={meta} />
props = { ...props, meta }

return <Suspense fallback={<Loading/>}>
<Layout {...props} />
</Suspense>
}

export async function getStaticProps({ params: { category } }) {
Expand Down
31 changes: 23 additions & 8 deletions pages/category/[category]/page/[page].js
Original file line number Diff line number Diff line change
@@ -1,23 +1,35 @@
import { getGlobalNotionData } from '@/lib/notion/getNotionData'
import React from 'react'
import React, { Suspense, useEffect, useState } from 'react'
import { useGlobal } from '@/lib/global'
import dynamic from 'next/dynamic'
import BLOG from '@/blog.config'

import Loading from '@/components/Loading'

/**
* 加载默认主题
*/
const DefaultLayout = dynamic(() => import(`@/themes/${BLOG.THEME}/LayoutCategory`), { ssr: true })

/**
* 分类页
* @param {*} props
* @returns
*/
export default function Category(props) {
const { theme } = useGlobal()
const { siteInfo, posts } = props
const { siteInfo } = props
const { locale } = useGlobal()
if (!posts) {
const Layout404 = dynamic(() => import(`@/themes/${theme}`).then(async (m) => { return m.Layout404 }), { ssr: true, loading: () => <Loading /> })
return <Layout404 {...props} />
}

const [Layout, setLayout] = useState(DefaultLayout)
// 切换主题
useEffect(() => {
const loadLayout = async () => {
setLayout(dynamic(() => import(`@/themes/${theme}/LayoutCategory`)))
}
loadLayout()
}, [theme])

const meta = {
title: `${props.category} | ${locale.COMMON.CATEGORY} | ${
siteInfo?.title || ''
Expand All @@ -28,8 +40,11 @@ export default function Category(props) {
type: 'website'
}

const LayoutCategory = dynamic(() => import(`@/themes/${theme}`).then(async (m) => { return m.LayoutCategory }), { ssr: true, loading: () => <Loading /> })
return <LayoutCategory {...props} meta={meta} />
props = { ...props, meta }

return <Suspense fallback={<Loading/>}>
<Layout {...props} />
</Suspense>
}

export async function getStaticProps({ params: { category, page } }) {
Expand Down
Loading

0 comments on commit 00d32c8

Please sign in to comment.