refactor: modularize typography layout structure

This commit is contained in:
2025-09-17 09:55:35 +08:00
parent 99b5383f84
commit edcb6cb794
9 changed files with 380 additions and 372 deletions

70
mhhung/README.md Normal file
View File

@@ -0,0 +1,70 @@
# Typography 主題架構說明
本專案是部落格佈景主題Typography主要透過 `index.js` 匯出多種佈局組件,方便在 Next.js / Notion-Blog 專案中依照情境載入。下方整理目前的檔案架構與各模組職責,以及常見的使用方式。
## 專案結構
```
.
├── components/ # 主題客製化的視覺組件TopBar、Footer、BlogPostBar…
├── config.js # 主題對外設定(標題、選單顯示開關…)
├── index.js # 封裝後的佈局出口,對外統一匯出
├── layouts/ # 各種頁面佈局拆分檔案
│ ├── ArchiveLayout.jsx # 文章歸檔頁
│ ├── BaseLayout.jsx # 共同外殼(搜尋、導覽、跳頂按鈕…)
│ ├── ListLayouts.jsx # 首頁、文章列表、搜尋列表
│ ├── NotFoundLayout.jsx # 404 頁面
│ ├── SlugLayout.jsx # 單篇文章頁
│ └── TaxonomyLayouts.jsx # 分類與標籤頁
├── style.js # 只針對此主題作用的全域樣式
└── utils/
└── groupArticlesByYear.js # 文章依年份分組的小工具
```
## 主要佈局與職責
- `LayoutBase`:最外層骨架,負責載入樣式、導覽列、頁尾、搜尋與 Loading 狀態,其他頁面內容會以 children 注入。
- `LayoutIndex` / `LayoutPostList`:顯示文章列表或首頁,會掛上 `BlogPostBar``BlogListPage`
- `LayoutSearch`:在文章列表基礎上,透過 `replaceSearchResult` 將關鍵字高亮。
- `LayoutArchive`:使用 `groupArticlesByYearArray` 將文章依年份分組後渲染。
- `LayoutSlug`:單篇文章頁面,負責文章資訊、廣告、前後文推薦與留言區。
- `LayoutCategoryIndex` / `LayoutTagIndex`:顯示分類與標籤的索引列表。
- `Layout404`:等待 Notion 內容載入後做導向,或直接顯示 404。
## 使用說明
1. **在 Next.js 主題系統中載入**
```jsx
import { LayoutBase, LayoutIndex } from 'mhhung'
const Home = props => (
<LayoutBase {...props}>
<LayoutIndex {...props} />
</LayoutBase>
)
export default Home
```
- `LayoutBase` 會處理共同外殼;`LayoutIndex` 則是此頁的實際內容。
- 其他頁面可依需求替換為 `LayoutArchive`、`LayoutSlug`…等對應佈局。
2. **設定主題參數**
- 編輯 `config.js`,可調整部落格名稱、是否展示分類/標籤/歸檔選單,以及文章推薦、封面等開關。
- 也可以透過環境變數(如 `NEXT_PUBLIC_TYPOGRAPHY_BLOG_NAME`)覆寫預設值,方便在不同部署環境中使用。
3. **擴充樣式或功能**
- 共用樣式可以在 `style.js` 中調整或新增。
- 若要新增新的頁面佈局,建議在 `layouts/` 下建立新的 JSX 檔案,並於 `index.js` 匯出,以維持統一入口。
- 共用的邏輯或工具函式,可集中在 `utils/` 目錄內,減少重複程式碼。
4. **整合既有元件**
- 所有 `layouts/` 中引用的元件皆放於 `components/`。若要替換視覺元素,如導覽列或頁尾,直接在對應元件修改即可。
- 動態載入 (`next/dynamic`) 會避免在 SSR 階段載入僅限瀏覽器的套件,若新增依賴,請依照既有範例設定 `ssr: false`。
## 開發建議
- 調整佈局時,先確認是否為共用邏輯(放在 `BaseLayout` 或工具函式),再決定是否要拆分。
- 新增功能建議寫在對應的 `layouts/` 或 `components/` 中,並保持檔案職責單一,讓後續維護更容易。
- 若有多語系或 Theme 變化需求,可以在 `config.js` 中增加新的設定值,並於各佈局透過 `siteConfig` 取得。
有任何額外需求都可以在 README 中持續補充,讓後續維護人員快速上手。

View File

@@ -1,372 +1,8 @@
import { AdSlot } from '@/components/GoogleAdsense'
import replaceSearchResult from '@/components/Mark'
import NotionPage from '@/components/NotionPage'
import { siteConfig } from '@/lib/config'
import { useGlobal } from '@/lib/global'
import { isBrowser } from '@/lib/utils'
import dynamic from 'next/dynamic'
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
import { createContext, useContext, useEffect, useRef } from 'react'
import BlogPostBar from './components/BlogPostBar'
import CONFIG from './config'
import { Style } from './style'
import Catalog from './components/Catalog'
const AlgoliaSearchModal = dynamic(
() => import('@/components/AlgoliaSearchModal'),
{ ssr: false }
)
// 主题组件
const BlogArchiveItem = dynamic(() => import('./components/BlogArchiveItem'), {
ssr: false
})
const ArticleLock = dynamic(() => import('./components/ArticleLock'), {
ssr: false
})
const ArticleInfo = dynamic(() => import('./components/ArticleInfo'), {
ssr: false
})
const Comment = dynamic(() => import('@/components/Comment'), { ssr: false })
const ArticleAround = dynamic(() => import('./components/ArticleAround'), {
ssr: false
})
const TopBar = dynamic(() => import('./components/TopBar'), { ssr: false })
const NavBar = dynamic(() => import('./components/NavBar'), { ssr: false })
const JumpToTopButton = dynamic(() => import('./components/JumpToTopButton'), {
ssr: false
})
const Footer = dynamic(() => import('./components/Footer'), { ssr: false })
const WWAds = dynamic(() => import('@/components/WWAds'), { ssr: false })
const BlogListPage = dynamic(() => import('./components/BlogListPage'), {
ssr: false
})
const RecommendPosts = dynamic(() => import('./components/RecommendPosts'), {
ssr: false
})
// 主题全局状态
const ThemeGlobalSimple = createContext()
export const useSimpleGlobal = () => useContext(ThemeGlobalSimple)
/**
* 基础布局
*
* @param {*} props
* @returns
*/
const LayoutBase = props => {
const { children } = props
const { onLoading, fullWidth } = useGlobal()
// const onLoading = true
const searchModal = useRef(null)
return (
<ThemeGlobalSimple.Provider value={{ searchModal }}>
<div
id='theme-typography'
className={`${siteConfig('FONT_STYLE')} font-typography h-screen flex flex-col dark:text-gray-300 bg-white dark:bg-[#232222] overflow-hidden`}>
<Style />
{siteConfig('SIMPLE_TOP_BAR', null, CONFIG) && <TopBar {...props} />}
<div className='flex flex-1 mx-auto overflow-hidden py-8 md:p-0 md:max-w-7xl md:px-24 w-screen'>
{/* 主体 - 使用 flex 布局 */}
{/* 文章详情才显示 */}
{/* {props.post && (
<div className='mt-20 hidden md:block md:fixed md:left-5 md:w-[300px]'>
<Catalog {...props} />
</div>
)} */}
<div className='overflow-hidden md:mt-20 flex-1 '>
{/* 左侧内容区域 - 可滚动 */}
<div
id='container-inner'
className='h-full w-full md:px-24 overflow-y-auto scroll-hidden relative'>
{/* 移动端导航 - 显示在顶部 */}
<div className='md:hidden'>
<NavBar {...props} />
</div>
{onLoading ? (
// loading 时显示 spinner
<div className='flex items-center justify-center min-h-[500px] w-full'>
<div className='animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-gray-900 dark:border-white'></div>
</div>
) : (
<>{children}</>
)}
<AdSlot type='native' />
{/* 移动端页脚 - 显示在底部 */}
<div className='md:hidden z-30 '>
<Footer {...props} />
</div>
</div>
</div>
{/* 右侧导航和页脚 - 固定不滚动 */}
<div className='hidden md:flex md:flex-col md:flex-shrink-0 md:h-[100vh] sticky top-20'>
<NavBar {...props} />
<Footer {...props} />
</div>
</div>
<div className='fixed right-4 bottom-4 z-20'>
<JumpToTopButton />
</div>
{/* 搜索框 */}
<AlgoliaSearchModal cRef={searchModal} {...props} />
</div>
</ThemeGlobalSimple.Provider>
)
}
/**
* 博客首页
* 首页就是列表
* @param {*} props
* @returns
*/
const LayoutIndex = props => {
return <LayoutPostList {...props} />
}
/**
* 博客列表
* @param {*} props
* @returns
*/
const LayoutPostList = props => {
return (
<>
<BlogPostBar {...props} />
<BlogListPage {...props} />
</>
)
}
/**
* 搜索页
* 也是博客列表
* @param {*} props
* @returns
*/
const LayoutSearch = props => {
const { keyword } = props
useEffect(() => {
if (isBrowser) {
replaceSearchResult({
doms: document.getElementById('posts-wrapper'),
search: keyword,
target: {
element: 'span',
className: 'text-red-500 border-b border-dashed'
}
})
}
}, [])
return <LayoutPostList {...props} />
}
function groupArticlesByYearArray(articles) {
const grouped = {};
for (const article of articles) {
const year = new Date(article.publishDate).getFullYear().toString();
if (!grouped[year]) {
grouped[year] = [];
}
grouped[year].push(article);
}
for (const year in grouped) {
grouped[year].sort((a, b) => b.publishDate - a.publishDate);
}
// 转成数组并按年份倒序
return Object.entries(grouped)
.sort(([a], [b]) => b - a)
.map(([year, posts]) => ({ year, posts }));
}
/**
* 归档页
* @param {*} props
* @returns
*/
const LayoutArchive = props => {
const { posts } = props
const sortPosts = groupArticlesByYearArray(posts)
return (
<>
<div className='mb-10 pb-20 md:pb-12 p-5 min-h-screen w-full'>
{sortPosts.map(p => (
<BlogArchiveItem
key={p.year}
archiveTitle={p.year}
archivePosts={p.posts}
/>
))}
</div>
</>
)
}
/**
* 文章详情
* @param {*} props
* @returns
*/
const LayoutSlug = props => {
const { post, lock, validPassword, prev, next, recommendPosts } = props
const { fullWidth } = useGlobal()
return (
<>
{lock && <ArticleLock validPassword={validPassword} />}
{!lock && post && (
<div
className={`px-5 pt-3 ${fullWidth ? '' : 'xl:max-w-4xl 2xl:max-w-6xl'}`}>
{/* 文章信息 */}
<ArticleInfo post={post} />
{/* 广告嵌入 */}
{/* <AdSlot type={'in-article'} /> */}
<WWAds orientation='horizontal' className='w-full' />
<div id='article-wrapper'>
{/* Notion 文章主体 */}
{!lock && <NotionPage post={post} />}
</div>
{/* 分享 */}
{/* <ShareBar post={post} /> */}
{/* 广告嵌入 */}
<AdSlot type={'in-article'} />
{post?.type === 'Post' && (
<>
<ArticleAround prev={prev} next={next} />
<RecommendPosts recommendPosts={recommendPosts} />
</>
)}
{/* 评论区 */}
<Comment frontMatter={post} />
</div>
)}
</>
)
}
/**
* 404
* @param {*} props
* @returns
*/
const Layout404 = props => {
const { post } = props
const router = useRouter()
const waiting404 = siteConfig('POST_WAITING_TIME_FOR_404') * 1000
useEffect(() => {
// 404
if (!post) {
setTimeout(() => {
if (isBrowser) {
const article = document.querySelector(
'#article-wrapper #notion-article'
)
if (!article) {
router.push('/404').then(() => {
console.warn('找不到页面', router.asPath)
})
}
}
}, waiting404)
}
}, [post])
return <>404 Not found.</>
}
/**
* 分类列表
* @param {*} props
* @returns
*/
const LayoutCategoryIndex = props => {
const { categoryOptions } = props
return (
<>
<div id='category-list' className='px-5 duration-200 flex flex-wrap'>
{categoryOptions?.map(category => {
return (
<SmartLink
key={category.name}
href={`/category/${category.name}`}
passHref
legacyBehavior>
<div
className={
'hover:text-black dark:hover:text-white dark:text-gray-300 dark:hover:bg-gray-600 px-5 cursor-pointer py-2 hover:bg-gray-100'
}>
<i className='mr-4 fas fa-folder' />
{category.name}({category.count})
</div>
</SmartLink>
)
})}
</div>
</>
)
}
/**
* 标签列表
* @param {*} props
* @returns
*/
const LayoutTagIndex = props => {
const { tagOptions } = props
return (
<>
<div id='tags-list' className='px-5 duration-200 flex flex-wrap'>
{tagOptions.map(tag => {
return (
<div key={tag.name} className='p-2'>
<SmartLink
key={tag}
href={`/tag/${encodeURIComponent(tag.name)}`}
passHref
className={`cursor-pointer inline-block rounded hover:bg-gray-500 hover:text-white duration-200 mr-2 py-1 px-2 text-xs whitespace-nowrap dark:hover:text-white text-gray-600 hover:shadow-xl dark:border-gray-400 notion-${tag.color}_background dark:bg-gray-800`}>
<div className='font-light dark:text-gray-400'>
<i className='mr-1 fas fa-tag' />{' '}
{tag.name + (tag.count ? `(${tag.count})` : '')}{' '}
</div>
</SmartLink>
</div>
)
})}
</div>
</>
)
}
export {
Layout404,
LayoutArchive,
LayoutBase,
LayoutCategoryIndex,
LayoutIndex,
LayoutPostList,
LayoutSearch,
LayoutSlug,
LayoutTagIndex,
CONFIG as THEME_CONFIG
}
export { LayoutBase, useSimpleGlobal } from './layouts/BaseLayout'
export { LayoutIndex, LayoutPostList, LayoutSearch } from './layouts/ListLayouts'
export { LayoutArchive } from './layouts/ArchiveLayout'
export { LayoutSlug } from './layouts/SlugLayout'
export { Layout404 } from './layouts/NotFoundLayout'
export { LayoutCategoryIndex, LayoutTagIndex } from './layouts/TaxonomyLayouts'
export { default as CONFIG } from './config'
export { default as THEME_CONFIG } from './config'

View File

@@ -0,0 +1,25 @@
import dynamic from 'next/dynamic'
import { groupArticlesByYearArray } from '../utils/groupArticlesByYear'
const BlogArchiveItem = dynamic(() => import('../components/BlogArchiveItem'), {
ssr: false
})
const LayoutArchive = props => {
const { posts } = props
const sortPosts = groupArticlesByYearArray(posts)
return (
<div className='mb-10 pb-20 md:pb-12 p-5 min-h-screen w-full'>
{sortPosts.map(p => (
<BlogArchiveItem
key={p.year}
archiveTitle={p.year}
archivePosts={p.posts}
/>
))}
</div>
)
}
export { LayoutArchive }

View File

@@ -0,0 +1,79 @@
import { AdSlot } from '@/components/GoogleAdsense'
import dynamic from 'next/dynamic'
import { createContext, useContext, useRef } from 'react'
import { siteConfig } from '@/lib/config'
import { useGlobal } from '@/lib/global'
import CONFIG from '../config'
import { Style } from '../style'
const AlgoliaSearchModal = dynamic(
() => import('@/components/AlgoliaSearchModal'),
{ ssr: false }
)
const TopBar = dynamic(() => import('../components/TopBar'), { ssr: false })
const NavBar = dynamic(() => import('../components/NavBar'), { ssr: false })
const JumpToTopButton = dynamic(
() => import('../components/JumpToTopButton'),
{
ssr: false
}
)
const Footer = dynamic(() => import('../components/Footer'), { ssr: false })
const ThemeGlobalSimple = createContext()
const useSimpleGlobal = () => useContext(ThemeGlobalSimple)
const LayoutBase = props => {
const { children } = props
const { onLoading } = useGlobal()
const searchModal = useRef(null)
return (
<ThemeGlobalSimple.Provider value={{ searchModal }}>
<div
id='theme-typography'
className={`${siteConfig('FONT_STYLE')} font-typography h-screen flex flex-col dark:text-gray-300 bg-white dark:bg-[#232222] overflow-hidden`}>
<Style />
{siteConfig('SIMPLE_TOP_BAR', null, CONFIG) && <TopBar {...props} />}
<div className='flex flex-1 mx-auto overflow-hidden py-8 md:p-0 md:max-w-7xl md:px-24 w-screen'>
<div className='overflow-hidden md:mt-20 flex-1 '>
<div
id='container-inner'
className='h-full w-full md:px-24 overflow-y-auto scroll-hidden relative'>
<div className='md:hidden'>
<NavBar {...props} />
</div>
{onLoading ? (
<div className='flex items-center justify-center min-h-[500px] w-full'>
<div className='animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-gray-900 dark:border-white'></div>
</div>
) : (
<>{children}</>
)}
<AdSlot type='native' />
<div className='md:hidden z-30 '>
<Footer {...props} />
</div>
</div>
</div>
<div className='hidden md:flex md:flex-col md:flex-shrink-0 md:h-[100vh] sticky top-20'>
<NavBar {...props} />
<Footer {...props} />
</div>
</div>
<div className='fixed right-4 bottom-4 z-20'>
<JumpToTopButton />
</div>
<AlgoliaSearchModal cRef={searchModal} {...props} />
</div>
</ThemeGlobalSimple.Provider>
)
}
export { LayoutBase, useSimpleGlobal }

View File

@@ -0,0 +1,39 @@
import dynamic from 'next/dynamic'
import { useEffect } from 'react'
import replaceSearchResult from '@/components/Mark'
import { isBrowser } from '@/lib/utils'
import BlogPostBar from '../components/BlogPostBar'
const BlogListPage = dynamic(() => import('../components/BlogListPage'), {
ssr: false
})
const LayoutPostList = props => (
<>
<BlogPostBar {...props} />
<BlogListPage {...props} />
</>
)
const LayoutIndex = props => <LayoutPostList {...props} />
const LayoutSearch = props => {
const { keyword } = props
useEffect(() => {
if (isBrowser) {
replaceSearchResult({
doms: document.getElementById('posts-wrapper'),
search: keyword,
target: {
element: 'span',
className: 'text-red-500 border-b border-dashed'
}
})
}
}, [keyword])
return <LayoutPostList {...props} />
}
export { LayoutIndex, LayoutPostList, LayoutSearch }

View File

@@ -0,0 +1,34 @@
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import { siteConfig } from '@/lib/config'
import { isBrowser } from '@/lib/utils'
const Layout404 = props => {
const { post } = props
const router = useRouter()
const waiting404 = siteConfig('POST_WAITING_TIME_FOR_404') * 1000
useEffect(() => {
if (post) {
return
}
const timer = setTimeout(() => {
if (!isBrowser) {
return
}
const article = document.querySelector('#article-wrapper #notion-article')
if (!article) {
router.push('/404').then(() => {
console.warn('找不到页面', router.asPath)
})
}
}, waiting404)
return () => clearTimeout(timer)
}, [post, router, waiting404])
return <>404 Not found.</>
}
export { Layout404 }

View File

@@ -0,0 +1,58 @@
import { AdSlot } from '@/components/GoogleAdsense'
import NotionPage from '@/components/NotionPage'
import { useGlobal } from '@/lib/global'
import dynamic from 'next/dynamic'
const ArticleLock = dynamic(() => import('../components/ArticleLock'), {
ssr: false
})
const ArticleInfo = dynamic(() => import('../components/ArticleInfo'), {
ssr: false
})
const Comment = dynamic(() => import('@/components/Comment'), { ssr: false })
const ArticleAround = dynamic(() => import('../components/ArticleAround'), {
ssr: false
})
const RecommendPosts = dynamic(() => import('../components/RecommendPosts'), {
ssr: false
})
const WWAds = dynamic(() => import('@/components/WWAds'), { ssr: false })
const LayoutSlug = props => {
const { post, lock, validPassword, prev, next, recommendPosts } = props
const { fullWidth } = useGlobal()
if (lock) {
return <ArticleLock validPassword={validPassword} />
}
if (!post) {
return null
}
const isPost = post?.type === 'Post'
return (
<div className={`px-5 pt-3 ${fullWidth ? '' : 'xl:max-w-4xl 2xl:max-w-6xl'}`}>
<ArticleInfo post={post} />
<WWAds orientation='horizontal' className='w-full' />
<div id='article-wrapper'>
<NotionPage post={post} />
</div>
<AdSlot type={'in-article'} />
{isPost && (
<>
<ArticleAround prev={prev} next={next} />
<RecommendPosts recommendPosts={recommendPosts} />
</>
)}
<Comment frontMatter={post} />
</div>
)
}
export { LayoutSlug }

View File

@@ -0,0 +1,46 @@
import SmartLink from '@/components/SmartLink'
const LayoutCategoryIndex = props => {
const { categoryOptions } = props
return (
<div id='category-list' className='px-5 duration-200 flex flex-wrap'>
{categoryOptions?.map(category => (
<SmartLink
key={category.name}
href={`/category/${category.name}`}
passHref
legacyBehavior>
<div className='hover:text-black dark:hover:text-white dark:text-gray-300 dark:hover:bg-gray-600 px-5 cursor-pointer py-2 hover:bg-gray-100'>
<i className='mr-4 fas fa-folder' />
{category.name}({category.count})
</div>
</SmartLink>
))}
</div>
)
}
const LayoutTagIndex = props => {
const { tagOptions } = props
return (
<div id='tags-list' className='px-5 duration-200 flex flex-wrap'>
{tagOptions.map(tag => (
<div key={tag.name} className='p-2'>
<SmartLink
key={tag}
href={`/tag/${encodeURIComponent(tag.name)}`}
passHref
className={`cursor-pointer inline-block rounded hover:bg-gray-500 hover:text-white duration-200 mr-2 py-1 px-2 text-xs whitespace-nowrap dark:hover:text-white text-gray-600 hover:shadow-xl dark:border-gray-400 notion-${tag.color}_background dark:bg-gray-800`}>
<div className='font-light dark:text-gray-400'>
<i className='mr-1 fas fa-tag' /> {tag.name + (tag.count ? `(${tag.count})` : '')}{' '}
</div>
</SmartLink>
</div>
))}
</div>
)
}
export { LayoutCategoryIndex, LayoutTagIndex }

View File

@@ -0,0 +1,21 @@
const groupArticlesByYearArray = articles => {
const grouped = {}
for (const article of articles) {
const year = new Date(article.publishDate).getFullYear().toString()
if (!grouped[year]) {
grouped[year] = []
}
grouped[year].push(article)
}
for (const year in grouped) {
grouped[year].sort((a, b) => b.publishDate - a.publishDate)
}
return Object.entries(grouped)
.sort(([a], [b]) => b - a)
.map(([year, posts]) => ({ year, posts }))
}
export { groupArticlesByYearArray }