fix(theme): reset theme due to error

This commit is contained in:
2025-09-18 00:26:47 +08:00
parent 49dab41935
commit ade57f0d1e
73 changed files with 415 additions and 3098 deletions

View File

@@ -1,82 +0,0 @@
# GitBook 主題架構說明
GitBook 主題提供類似線上文件的閱讀體驗:左側為樹狀導覽、右側顯示文章資訊與公告,內頁則專注呈現 Notion 內容。本文件整理主題的檔案結構、各佈局元件的責任分工,以及常見的使用方式,方便日後整合或擴充。
## 專案結構
```
.
├── components/ # 主題專用的視覺元件與工具(導覽清單、目錄抽屜、底部工具列…)
│ └── ui/dashboard/ # 儀表板頁面使用的額外組件
├── config.js # 主題設定首頁導向、導覽開關、Widget 等)
├── index.js # 統一對外匯出的入口
├── layouts/ # 依頁面職責拆分的佈局元件
│ ├── ArchiveLayout.jsx # 歸檔頁
│ ├── AuthLayouts.jsx # 登入/註冊頁
│ ├── BaseLayout.jsx # 主架構左右欄、行動裝置導覽、Loading 與廣告
│ ├── ListLayouts.jsx # 首頁/文章列表/搜尋結果與儀表板
│ ├── NotFoundLayout.jsx # 404 頁面
│ ├── SlugLayout.jsx # 文章詳情頁
│ └── TaxonomyLayouts.jsx # 分類與標籤索引
├── style.js # 只對 GitBook 主題生效的全域樣式
└── README.md # 本說明文件
```
## 主要佈局與職責
- `LayoutBase`:包住所有內容的骨架,負責導覽抽屜、公告、目錄、回頂按鈕與 Loading 遮罩,並透過 `useGitBookGlobal` 共享狀態搜尋、TOC、導覽列表
- `LayoutIndex`:讀取 `config.js``GITBOOK_INDEX_PAGE`,在前端重新導向至指定文章,若找不到對應 slug 會注入錯誤提示。
- `LayoutPostList` / `LayoutSearch`:此主題採左側導覽管理文章,頁面本身僅回傳空節點,確保路由存在。
- `LayoutArchive`:使用 `BlogArchiveItem` 依年份渲染歸檔清單。
- `LayoutSlug`顯示單篇內容處理加密文章、Meta 標題、分類/標籤、前後篇與留言,並在內容缺漏時自動導回 404。
- `LayoutCategoryIndex` / `LayoutTagIndex`:輸出分類與標籤的索引列表,套用統一樣式與 `locale` 文案。
- `LayoutSignIn` / `LayoutSignUp`Clerk 驗證元件容器,會先顯示官方預設表單,再渲染 Notion 內容。
- `LayoutDashboard`:搭配 `components/ui/dashboard/*` 顯示自訂儀表板。
- `Layout404`:延遲檢查內容載入狀態,若仍無法抓到文章容器便導回首頁。
## 使用說明
1. **在 Next.js 匯入主題佈局**
```jsx
import {
LayoutBase,
LayoutSlug,
LayoutIndex,
LayoutCategoryIndex
} from '@/themes/gitbook'
const Post = props => (
<LayoutBase {...props}>
<LayoutSlug {...props} />
</LayoutBase>
)
export default Post
```
- `LayoutBase` 處理共同框架;內層依頁面需求替換為 `LayoutIndex`、`LayoutArchive`、`LayoutCategoryIndex`…等。
- 需要使用 TOC 或導覽狀態時,可透過 `useGitBookGlobal()` 取得 `searchModal`、`tocVisible` 等共享資料。
2. **調整主題設定**
- 於 `config.js` 修改選項,或透過環境變數覆寫,例如 `NEXT_PUBLIC_GITBOOK_INDEX_PAGE`、`NEXT_PUBLIC_GITBOOK_AUTO_SORT`。
- 常用開關:
- `GITBOOK_AUTO_SORT`:自動依分類整理導覽。
- `GITBOOK_EXCLUSIVE_COLLAPSE`:導覽是否一次只展開一組。
- `GITBOOK_FOLDER_HOVER_EXPAND`:滑鼠懸停是否自動展開導覽資料夾。
- `GITBOOK_WIDGET_REVOLVER_MAPS` / `GITBOOK_WIDGET_TO_TOP`:控制右側 Widget。
3. **客製樣式與元件**
- 全域樣式集中在 `style.js`,若需調整字體或底色可於此擴充。
- 導覽列表、公告、底部工具列等都在 `components/`,可直接替換或新增對應元件。
- 儀表板相關 UI 放在 `components/ui/dashboard/`,可拆分或擴充模組化功能。
4. **新增頁面佈局**
- 建議在 `layouts/` 下新增檔案並於 `index.js` 匯出,維持與現有架構一致。
- 若需要共用狀態,可在新佈局內透過 `useGitBookGlobal` 共享資料,避免重複定義內容。
## 開發提醒
- 本主題內的註解與靜態文字皆已改為臺灣常用的繁體中文,若新增內容請維持相同用語風格。
- 導覽列表仰賴 `allNavPages`,若調整資料格式請同步更新 `NavPostList` 相關邏輯。
- 重新導向或動態載入元件時請注意瀏覽器環境判斷(`isBrowser`),避免在 SSR 階段觸發錯誤。
如需額外備註,可持續更新本 README 讓後續維護者快速上手。

View File

@@ -1,21 +0,0 @@
// import { useGlobal } from '@/lib/global'
import dynamic from 'next/dynamic'
const NotionPage = dynamic(() => import('@/components/NotionPage'))
const Announcement = ({ notice, className }) => {
// const { locale } = useGlobal()
if (notice?.blockMap) {
return <div className={className}>
<section id='announcement-wrapper' className="dark:text-gray-300 rounded-xl px-2 py-4">
{/* <div><i className='mr-2 fas fa-bullhorn' />{locale.COMMON.ANNOUNCEMENT}</div> */}
{notice && (<div id="announcement-content">
<NotionPage post={notice} />
</div>)}
</section>
</div>
} else {
return <></>
}
}
export default Announcement

View File

@@ -1,41 +0,0 @@
import { useGlobal } from '@/lib/global'
import SmartLink from '@/components/SmartLink'
/**
* 上一篇、下一篇文章
* @param {prev,next} param0
* @returns
*/
export default function ArticleAround({ prev, next }) {
const { locale } = useGlobal()
if (!prev || !next) {
return <></>
}
return (
<section className='text-gray-800 dark:text-gray-400 flex items-center justify-between gap-x-3 my-4'>
<SmartLink
href={prev.href}
passHref
className='rounded border w-full h-20 px-3 cursor-pointer justify-between items-center flex hover:text-green-500 duration-300'>
<i className='mr-1 fas fa-angle-left' />
<div>
<div>{locale.COMMON.PREV_POST}</div>
<div>{prev.title}</div>
</div>
</SmartLink>
<SmartLink
href={next.href}
passHref
className='rounded border w-full h-20 px-3 cursor-pointer justify-between items-center flex hover:text-green-500 duration-300'>
<div>
<div>{locale.COMMON.NEXT_POST}</div>
<div> {next.title}</div>
</div>
<i className='ml-1 my-1 fas fa-angle-right' />
</SmartLink>
</section>
)
}

View File

@@ -1,17 +0,0 @@
/**
* 文章補充資訊
* @param {*} param0
* @returns
*/
export default function ArticleInfo({ post }) {
if (!post) {
return null
}
return (
<div className='pt-10 pb-6 text-gray-400 text-sm'>
<i className='fa-regular fa-clock mr-1' />
Last update:{' '}
{post.date?.start_date || post?.publishDay || post?.lastEditedDay}
</div>
)
}

View File

@@ -1,67 +0,0 @@
import { useGlobal } from '@/lib/global'
import { useRouter } from 'next/router'
import { useEffect, useRef } from 'react'
/**
* 加密文章驗證元件
* @param {password, validPassword} props
* @param password 正確的密碼
* @param validPassword(bool) 回呼函式,驗證通過時傳回 true
* @returns
*/
export const ArticleLock = props => {
const { validPassword } = props
const { locale } = useGlobal()
const router = useRouter()
const passwordInputRef = useRef(null)
/**
* 輸入並送出密碼
*/
const submitPassword = () => {
const p = document.getElementById('password')
// 驗證失敗提示
if (!validPassword(p?.value)) {
const tips = document.getElementById('tips')
if (tips) {
tips.innerHTML = ''
tips.innerHTML = `<div class='text-red-500 animate__shakeX animate__animated'>${locale.COMMON.PASSWORD_ERROR}</div>`
}
}
}
useEffect(() => {
// 選取密碼輸入框並聚焦
passwordInputRef.current.focus()
}, [router])
return (
<div
id='container'
className='w-full flex justify-center items-center h-96 '>
<div className='text-center space-y-3'>
<div className='font-bold'>{locale.COMMON.ARTICLE_LOCK_TIPS}</div>
<div className='flex mx-4'>
<input
id='password'
type='password'
onKeyDown={e => {
if (e.key === 'Enter') {
submitPassword()
}
}}
ref={passwordInputRef} // 綁定 ref 到 passwordInputRef 變數
className='outline-none w-full text-sm pl-5 rounded-l transition focus:shadow-lg dark:text-gray-300 font-light leading-10 text-black bg-gray-100 dark:bg-gray-500'></input>
<div
onClick={submitPassword}
className='px-3 whitespace-nowrap cursor-pointer items-center justify-center py-2 bg-green-500 hover:bg-green-400 text-white rounded-r duration-300'>
<i className={'duration-200 cursor-pointer fas fa-key'}>
&nbsp;{locale.COMMON.SUBMIT}
</i>
</div>
</div>
<div id='tips'></div>
</div>
</div>
)
}

View File

@@ -1,36 +0,0 @@
import SmartLink from '@/components/SmartLink'
/**
* 歸檔分組
* @param {*} param0
* @returns
*/
export default function BlogArchiveItem({ archiveTitle, archivePosts }) {
return (
<div key={archiveTitle}>
<div id={archiveTitle} className='pt-16 pb-4 text-3xl dark:text-gray-300'>
{archiveTitle}
</div>
<ul>
{archivePosts[archiveTitle]?.map(post => {
return (
<li
key={post.id}
className='border-l-2 p-1 text-xs md:text-base items-center hover:scale-x-105 hover:border-gray-500 dark:hover:border-gray-300 dark:border-gray-400 transform duration-500'>
<div id={post?.publishDay}>
<span className='text-gray-400'>{post.date?.start_date}</span>{' '}
&nbsp;
<SmartLink
passHref
href={post?.href}
className='dark:text-gray-400 dark:hover:text-gray-300 overflow-x-hidden hover:underline cursor-pointer text-gray-600'>
{post.title}
</SmartLink>
</div>
</li>
)
})}
</ul>
</div>
)
}

View File

@@ -1,33 +0,0 @@
import Badge from '@/components/Badge'
import NotionIcon from '@/components/NotionIcon'
import { siteConfig } from '@/lib/config'
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
const BlogPostCard = ({ post, className }) => {
const router = useRouter()
const currentSelected =
decodeURIComponent(router.asPath.split('?')[0]) === post?.href
return (
<SmartLink href={post?.href} passHref>
<div
key={post.id}
className={`${className} relative py-1.5 cursor-pointer px-1.5 rounded-md hover:bg-gray-50
${currentSelected ? 'text-green-500 dark:bg-yellow-100 dark:text-yellow-600 font-semibold' : ' dark:hover:bg-yellow-100 dark:hover:text-yellow-600'}`}>
<div className='w-full select-none'>
{siteConfig('POST_TITLE_ICON') && (
<NotionIcon icon={post?.pageIcon} />
)}{' '}
{post.title}
</div>
{/* 最新文章加個紅點 */}
{post?.isLatest && siteConfig('GITBOOK_LATEST_POST_RED_BADGE') && (
<Badge />
)}
</div>
</SmartLink>
)
}
export default BlogPostCard

View File

@@ -1,50 +0,0 @@
import { useGlobal } from '@/lib/global'
import { useGitBookGlobal } from '..'
/**
* 行動版底部導覽
* @param {*} param0
* @returns
*/
export default function BottomMenuBar({ post, className }) {
const showTocButton = post?.toc?.length > 1
const { locale } = useGlobal()
const { pageNavVisible, changePageNavVisible, tocVisible, changeTocVisible } =
useGitBookGlobal()
const togglePageNavVisible = () => {
changePageNavVisible(!pageNavVisible)
}
const toggleToc = () => {
changeTocVisible(!tocVisible)
}
return (
<div className='md:hidden fixed bottom-0 left-0 z-50 w-full h-16 bg-white border-t border-gray-200 dark:bg-gray-700 dark:border-gray-600'>
<div
className={`grid h-full max-w-lg mx-auto font-medium ${showTocButton && 'grid-cols-2'}`}>
<button
type='button'
onClick={togglePageNavVisible}
className='inline-flex flex-col items-center justify-center px-5 border-gray-200 border-x hover:bg-gray-50 dark:hover:bg-gray-800 group dark:border-gray-600'>
<i className='fa-book fas w-5 h-5 mb-2 text-gray-500 dark:text-gray-400 group-hover:text-gray-600 dark:group-hover:text-gray-500' />
<span className='text-sm text-gray-500 dark:text-gray-400 group-hover:text-gray-600 dark:group-hover:text-gray-500'>
{locale.COMMON.ARTICLE_LIST}
</span>
</button>
{showTocButton && (
<button
type='button'
onClick={toggleToc}
className='inline-flex flex-col items-center justify-center px-5 border-gray-200 border-x hover:bg-gray-50 dark:hover:bg-gray-800 group dark:border-gray-600'>
<i className='fa-list-ol fas w-5 h-5 mb-2 text-gray-500 dark:text-gray-400 group-hover:text-gray-600 dark:group-hover:text-gray-500' />
<span class='text-sm text-gray-500 dark:text-gray-400 group-hover:text-gray-600 dark:group-hover:text-gray-500'>
{locale.COMMON.TABLE_OF_CONTENTS}
</span>
</button>
)}
</div>
</div>
)
}

View File

@@ -1,9 +0,0 @@
const Card = ({ children, headerSlot, className }) => {
return <div className={className}>
<>{headerSlot}</>
<section className="shadow px-2 py-4 bg-white dark:bg-gray-800 hover:shadow-xl duration-200">
{children}
</section>
</div>
}
export default Card

View File

@@ -1,104 +0,0 @@
import { isBrowser } from '@/lib/utils'
import throttle from 'lodash.throttle'
import { uuidToId } from 'notion-utils'
import { useCallback, useEffect, useState } from 'react'
/**
* 目錄導覽元件
* @param toc
* @returns {JSX.Element}
* @constructor
*/
const Catalog = ({ post }) => {
const toc = post?.toc
// 同步選取目錄事件
const [activeSection, setActiveSection] = useState(null)
// 監聽捲動事件
useEffect(() => {
window.addEventListener('scroll', actionSectionScrollSpy)
actionSectionScrollSpy()
return () => {
window.removeEventListener('scroll', actionSectionScrollSpy)
}
}, [post])
const throttleMs = 200
const actionSectionScrollSpy = useCallback(
throttle(() => {
const sections = document.getElementsByClassName('notion-h')
let prevBBox = null
let currentSectionId = null
for (let i = 0; i < sections.length; ++i) {
const section = sections[i]
if (!section || !(section instanceof Element)) continue
if (!currentSectionId) {
currentSectionId = section.getAttribute('data-id')
}
const bbox = section.getBoundingClientRect()
const prevHeight = prevBBox ? bbox.top - prevBBox.bottom : 0
const offset = Math.max(150, prevHeight / 4)
// GetBoundingClientRect returns values relative to viewport
if (bbox.top - offset < 0) {
currentSectionId = section.getAttribute('data-id')
prevBBox = bbox
continue
}
// No need to continue loop, if last element has been detected
break
}
setActiveSection(currentSectionId)
const tocIds = post?.toc?.map(t => uuidToId(t.id)) || []
const index = tocIds.indexOf(currentSectionId) || 0
if (isBrowser && tocIds?.length > 0) {
for (const tocWrapper of document?.getElementsByClassName(
'toc-wrapper'
)) {
tocWrapper?.scrollTo({ top: 28 * index, behavior: 'smooth' })
}
}
}, throttleMs)
)
// 無目錄則直接返回空
if (!toc || toc?.length < 1) {
return <></>
}
return (
<>
{/* <div className='w-full hidden md:block'>
<i className='mr-1 fas fa-stream' />{locale.COMMON.TABLE_OF_CONTENTS}
</div> */}
<div
id='toc-wrapper'
className='toc-wrapper overflow-y-auto my-2 max-h-80 overscroll-none scroll-hidden'>
<nav className='h-full text-black'>
{toc?.map(tocItem => {
const id = uuidToId(tocItem.id)
return (
<a
key={id}
href={`#${id}`}
// notion-table-of-contents-item
className={`${activeSection === id && 'border-green-500 text-green-500 font-bold'} border-l pl-4 block hover:text-green-500 border-lduration-300 transform font-light dark:text-gray-300
notion-table-of-contents-item-indent-level-${tocItem.indentLevel} catalog-item `}>
<span
style={{
display: 'inline-block',
marginLeft: tocItem.indentLevel * 16
}}
className={`truncate`}>
{tocItem.text}
</span>
</a>
)
})}
</nav>
</div>
</>
)
}
export default Catalog

View File

@@ -1,66 +0,0 @@
import { useGlobal } from '@/lib/global'
import { useGitBookGlobal } from '@/themes/gitbook'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import Catalog from './Catalog'
/**
* 懸浮抽屜目錄
* @param toc
* @param post
* @returns {JSX.Element}
* @constructor
*/
const CatalogDrawerWrapper = ({ post, cRef }) => {
const { tocVisible, changeTocVisible } = useGitBookGlobal()
const { locale } = useGlobal()
const router = useRouter()
const switchVisible = () => {
changeTocVisible(!tocVisible)
}
useEffect(() => {
changeTocVisible(false)
}, [router])
return (
<>
<div
id='gitbook-toc-float'
className='fixed top-0 right-0 z-40 md:hidden'>
{/* 側邊選單 */}
<div
className={
(tocVisible
? 'animate__slideInRight '
: ' -mr-72 animate__slideOutRight') +
' overflow-y-hidden shadow-card w-60 duration-200 fixed right-1 bottom-16 rounded py-2 bg-white dark:bg-hexo-black-gray'
}>
{post && (
<>
<div className='px-4 pb-2 flex justify-between items-center border-b font-bold'>
<span>{locale.COMMON.TABLE_OF_CONTENTS}</span>
<i
className='fas fa-times p-1 cursor-pointer'
onClick={() => {
changeTocVisible(false)
}}></i>
</div>
<div className='dark:text-gray-400 text-gray-600 px-3'>
<Catalog post={post} />
</div>
</>
)}
</div>
</div>
{/* 背景遮罩 */}
<div
id='right-drawer-background'
className={
(tocVisible ? 'block' : 'hidden') +
' fixed top-0 left-0 z-30 w-full h-full'
}
onClick={switchVisible}
/>
</>
)
}
export default CatalogDrawerWrapper

View File

@@ -1,19 +0,0 @@
import CategoryItem from './CategoryItem'
const CategoryGroup = ({ currentCategory, categoryOptions }) => {
if (!categoryOptions) {
return <></>
}
return <div id='category-list' className='pt-4'>
<div className='mb-2'><i className='mr-2 fas fa-th' />分類</div>
<div className='flex flex-wrap'>
{categoryOptions?.map(category => {
const selected = currentCategory === category.name
return <CategoryItem key={category.name} selected={selected} category={category.name} categoryCount={category.count} />
})}
</div>
</div>
}
export default CategoryGroup

View File

@@ -1,18 +0,0 @@
import SmartLink from '@/components/SmartLink'
export default function CategoryItem ({ selected, category, categoryCount }) {
return (
<SmartLink
href={`/category/${category}`}
passHref
className={(selected
? 'hover:text-white dark:hover:text-white bg-green-600 text-white '
: 'dark:text-green-400 text-gray-500 hover:text-white dark:hover:text-white hover:bg-green-600') +
' flex text-sm items-center duration-300 cursor-pointer py-1 font-light px-2 whitespace-nowrap'}>
<div><i className={`mr-2 fas ${selected ? 'fa-folder-open' : 'fa-folder'}`} />{category} {categoryCount && `(${categoryCount})`}
</div>
</SmartLink>
);
}

View File

@@ -1,66 +0,0 @@
import { BeiAnGongAn } from '@/components/BeiAnGongAn'
import { siteConfig } from '@/lib/config'
import SocialButton from './SocialButton'
/**
* 站點也叫
* @param {*} param0
* @returns
*/
const Footer = ({ siteInfo }) => {
const d = new Date()
const currentYear = d.getFullYear()
const since = siteConfig('SINCE')
const copyrightDate =
parseInt(since) < currentYear ? since + '-' + currentYear : currentYear
return (
<footer className='z-20 border p-2 rounded-lg bg:white dark:border-black dark:bg-hexo-black-gray justify-center text-center w-full text-sm relative'>
<SocialButton />
<div className='flex justify-center'>
<div>
<i className='mx-1 animate-pulse fas fa-heart' />{' '}
<a
href={siteConfig('LINK')}
className='underline font-bold text-gray-500 dark:text-gray-300 '>
{siteConfig('AUTHOR')}
</a>
.<br />
</div>
© {`${copyrightDate}`}
</div>
{siteConfig('BEI_AN') && (
<>
<i className='fas fa-shield-alt' />{' '}
<a href={siteConfig('BEI_AN_LINK')} className='mr-2'>
{siteConfig('BEI_AN')}
</a>
<BeiAnGongAn />
<br />
</>
)}
<span className='hidden busuanzi_container_site_pv'>
<i className='fas fa-eye' />
<span className='px-1 busuanzi_value_site_pv'> </span>{' '}
</span>
<span className='pl-2 hidden busuanzi_container_site_uv'>
<i className='fas fa-users' />{' '}
<span className='px-1 busuanzi_value_site_uv'> </span>{' '}
</span>
<div className='text-xs font-serif'>
Powered By{' '}
<a
href='https://github.com/tangly1024/NotionNext'
className='underline text-gray-500 dark:text-gray-300'>
NotionNext {siteConfig('VERSION')}
</a>
</div>
{/* SEO title */}
<h1 className='pt-1 hidden'>{siteConfig('TITLE')}</h1>
</footer>
)
}
export default Footer

View File

@@ -1,134 +0,0 @@
import Collapse from '@/components/Collapse'
import DarkModeButton from '@/components/DarkModeButton'
import { siteConfig } from '@/lib/config'
import { useGlobal } from '@/lib/global'
import { SignInButton, SignedOut, UserButton } from '@clerk/nextjs'
import { useRef, useState } from 'react'
import CONFIG from '../config'
import LogoBar from './LogoBar'
import { MenuBarMobile } from './MenuBarMobile'
import { MenuItemDrop } from './MenuItemDrop'
import SearchInput from './SearchInput'
/**
* 頁首:頂部導覽列 + 選單
* @param {} param0
* @returns
*/
export default function Header(props) {
const { className, customNav, customMenu } = props
const [isOpen, changeShow] = useState(false)
const collapseRef = useRef(null)
const { locale } = useGlobal()
const defaultLinks = [
{
icon: 'fas fa-th',
name: locale.COMMON.CATEGORY,
href: '/category',
show: siteConfig('GITBOOK_MENU_CATEGORY', null, CONFIG)
},
{
icon: 'fas fa-tag',
name: locale.COMMON.TAGS,
href: '/tag',
show: siteConfig('GITBOOK_BOOK_MENU_TAG', null, CONFIG)
},
{
icon: 'fas fa-archive',
name: locale.NAV.ARCHIVE,
href: '/archive',
show: siteConfig('GITBOOK_MENU_ARCHIVE', null, CONFIG)
},
{
icon: 'fas fa-search',
name: locale.NAV.SEARCH,
href: '/search',
show: siteConfig('GITBOOK_MENU_SEARCH', null, CONFIG)
}
]
let links = defaultLinks.concat(customNav)
const toggleMenuOpen = () => {
changeShow(!isOpen)
}
// 若啟用自訂選單則覆寫頁面內建選單
if (siteConfig('CUSTOM_MENU')) {
links = customMenu
}
const enableClerk = process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
return (
<div id='top-nav' className={'fixed top-0 w-full z-20 ' + className}>
{/* 桌面端選單 */}
<div className='flex justify-center border-b dark:border-black items-center w-full h-16 bg-white dark:bg-hexo-black-gray'>
<div className='px-5 max-w-screen-4xl w-full flex gap-x-3 justify-between items-center'>
{/* 左側 */}
<div className='flex'>
<LogoBar {...props} />
{/* 桌面端頂部選單 */}
<div className='hidden md:flex'>
{links &&
links?.map((link, index) => (
<MenuItemDrop key={index} link={link} />
))}
</div>
</div>
{/* 右側 */}
<div className='flex items-center gap-4'>
{/* 登入相關 */}
{enableClerk && (
<>
<SignedOut>
<SignInButton mode='modal'>
<button className='bg-green-500 hover:bg-green-600 text-white rounded-lg px-3 py-2'>
{locale.COMMON.SIGN_IN}
</button>
</SignInButton>
</SignedOut>
<UserButton />
</>
)}
<DarkModeButton className='text-sm items-center h-full hidden md:flex' />
<SearchInput className='hidden md:flex md:w-52 lg:w-72' />
{/* 摺疊按鈕,僅行動版顯示 */}
<div className='mr-1 flex md:hidden justify-end items-center space-x-4 dark:text-gray-200'>
<DarkModeButton className='flex text-md items-center h-full' />
<div
onClick={toggleMenuOpen}
className='cursor-pointer text-lg hover:scale-110 duration-150'>
{isOpen ? (
<i className='fas fa-times' />
) : (
<i className='fa-solid fa-bars' />
)}
</div>
</div>
</div>
</div>
</div>
{/* 行動版摺疊選單 */}
<Collapse
type='vertical'
collapseRef={collapseRef}
isOpen={isOpen}
className='md:hidden'>
<div className='bg-white dark:bg-hexo-black-gray pt-1 py-2 lg:hidden '>
<MenuBarMobile
{...props}
onHeightChange={param =>
collapseRef.current?.updateCollapseHeight(param)
}
/>
</div>
</Collapse>
</div>
)
}

View File

@@ -1,20 +0,0 @@
import LazyImage from '@/components/LazyImage'
import Router from 'next/router'
import SocialButton from './SocialButton'
import { siteConfig } from '@/lib/config'
const InfoCard = (props) => {
const { siteInfo } = props
return <div id='info-card' className='py-4'>
<div className='items-center justify-center'>
<div className='hover:scale-105 transform duration-200 cursor-pointer flex justify-center' onClick={ () => { Router.push('/about') }}>
<LazyImage src={siteInfo?.icon} className='rounded-full' width={120} alt={siteConfig('AUTHOR')}/>
</div>
<div className='text-xl py-2 hover:scale-105 transform duration-200 flex justify-center dark:text-gray-300'>{siteConfig('AUTHOR')}</div>
<div className='font-light text-gray-600 mb-2 hover:scale-105 transform duration-200 flex justify-center dark:text-gray-400'>{siteConfig('BIO')}</div>
<SocialButton/>
</div>
</div>
}
export default InfoCard

View File

@@ -1,28 +0,0 @@
/**
* 跳轉至網頁頂端
* 當畫面往下滑 500 像素後會顯示此元件
* @param targetRef 關聯高度的目標 HTML 標籤
* @param showPercent 是否顯示百分比
* @returns {JSX.Element}
* @constructor
*/
const JumpToTopButton = ({ showPercent = false, percent, className }) => {
return (
<div
id='jump-to-top'
data-aos='fade-up'
data-aos-duration='300'
data-aos-once='false'
data-aos-anchor-placement='top-center'
className='fixed xl:right-96 xl:mr-20 right-2 bottom-24 z-20'>
<i
className='shadow fas fa-chevron-up cursor-pointer p-2 rounded-full border bg-white dark:bg-hexo-black-gray'
onClick={() => {
window.scrollTo({ top: 0, behavior: 'smooth' })
}}
/>
</div>
)
}
export default JumpToTopButton

View File

@@ -1,15 +0,0 @@
import SmartLink from '@/components/SmartLink'
export default function LeftMenuBar () {
return (
<div className='w-20 border-r hidden lg:block pt-12'>
<section>
<SmartLink href='/' legacyBehavior>
<div className='text-center cursor-pointer hover:text-black'>
<i className='fas fa-home text-gray-500'/>
</div>
</SmartLink>
</section>
</div>
);
}

View File

@@ -1,29 +0,0 @@
import LazyImage from '@/components/LazyImage'
import { siteConfig } from '@/lib/config'
import SmartLink from '@/components/SmartLink'
import CONFIG from '../config'
/**
* Logo 區域
* @param {*} props
* @returns
*/
export default function LogoBar(props) {
const { siteInfo } = props
return (
<div id='logo-wrapper' className='w-full flex items-center mr-2'>
<SmartLink
href={`/${siteConfig('GITBOOK_INDEX_PAGE', '', CONFIG)}`}
className='flex text-lg font-bold md:text-2xl dark:text-gray-200 items-center'>
<LazyImage
src={siteInfo?.icon}
width={24}
height={24}
alt={siteConfig('AUTHOR')}
className='mr-2 hidden md:block '
/>
{siteInfo?.title || siteConfig('TITLE')}
</SmartLink>
</div>
)
}

View File

@@ -1,54 +0,0 @@
import { siteConfig } from '@/lib/config'
import { useGlobal } from '@/lib/global'
import CONFIG from '../config'
import { MenuItemCollapse } from './MenuItemCollapse'
export const MenuBarMobile = props => {
const { customMenu, customNav } = props
const { locale } = useGlobal()
let links = [
// { name: locale.NAV.INDEX, href: '/' || '/', show: true },
{
name: locale.COMMON.CATEGORY,
href: '/category',
show: siteConfig('GITBOOK_MENU_CATEGORY', null, CONFIG)
},
{
name: locale.COMMON.TAGS,
href: '/tag',
show: siteConfig('GITBOOK_BOOK_MENU_TAG', null, CONFIG)
},
{
name: locale.NAV.ARCHIVE,
href: '/archive',
show: siteConfig('GITBOOK_MENU_ARCHIVE', null, CONFIG)
}
// { name: locale.NAV.SEARCH, href: '/search', show: siteConfig('MENU_SEARCH', null, CONFIG) }
]
if (customNav) {
links = links.concat(customNav)
}
// 若啟用自訂選單,則不再使用 Page 生成的選單。
if (siteConfig('CUSTOM_MENU')) {
links = customMenu
}
if (!links || links.length === 0) {
return null
}
return (
<nav id='nav' className=' text-md'>
{links?.map((link, index) => (
<MenuItemCollapse
onHeightChange={props.onHeightChange}
key={index}
link={link}
/>
))}
</nav>
)
}

View File

@@ -1,97 +0,0 @@
import Collapse from '@/components/Collapse'
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
import { useState } from 'react'
/**
* 摺疊選單
* @param {*} param0
* @returns
*/
export const MenuItemCollapse = props => {
const { link } = props
const [show, changeShow] = useState(false)
const hasSubMenu = link?.subMenus?.length > 0
const [isOpen, changeIsOpen] = useState(false)
const router = useRouter()
if (!link || !link.show) {
return null
}
const selected = router.pathname === link.href || router.asPath === link.href
const toggleShow = () => {
changeShow(!show)
}
const toggleOpenSubMenu = () => {
changeIsOpen(!isOpen)
}
return (
<>
<div
className={
(selected
? 'bg-green-600 text-white hover:text-white'
: 'hover:text-green-600') +
' px-7 w-full text-left duration-200 dark:bg-hexo-black-gray dark:border-black'
}
onClick={toggleShow}>
{!hasSubMenu && (
<SmartLink
href={link?.href}
target={link?.target}
className='py-2 w-full my-auto items-center justify-between flex '>
<div>
<div className={`${link.icon} text-center w-4 mr-4`} />
{link.name}
</div>
</SmartLink>
)}
{hasSubMenu && (
<div
onClick={hasSubMenu ? toggleOpenSubMenu : null}
className='py-2 font-extralight flex justify-between cursor-pointer dark:text-gray-200 no-underline tracking-widest'>
<div>
<div className={`${link.icon} text-center w-4 mr-4`} />
{link.name}
</div>
<div className='inline-flex items-center '>
<i
className={`px-2 fas fa-chevron-right transition-all duration-200 ${isOpen ? 'rotate-90' : ''}`}></i>
</div>
</div>
)}
</div>
{/* 摺疊子選單 */}
{hasSubMenu && (
<Collapse isOpen={isOpen} onHeightChange={props.onHeightChange}>
{link?.subMenus?.map((sLink, index) => {
return (
<div
key={index}
className='
not:last-child:border-b-0 border-b dark:border-gray-800 py-2 px-14 cursor-pointer hover:bg-gray-100 dark:text-gray-200
font-extralight dark:bg-black text-left justify-start text-gray-600 bg-gray-50 dark:hover:bg-gray-900 tracking-widest transition-all duration-200'>
<SmartLink href={sLink.href} target={link?.target}>
<div>
<div
className={`${sLink.icon} text-center w-3 mr-3 text-xs`}
/>
{sLink.title}
</div>
</SmartLink>
</div>
)
})}
</Collapse>
)}
</>
)
}

View File

@@ -1,73 +0,0 @@
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
import { useState } from 'react'
export const MenuItemDrop = ({ link }) => {
const [show, changeShow] = useState(false)
const router = useRouter()
if (!link || !link.show) {
return null
}
const hasSubMenu = link?.subMenus?.length > 0
const selected = router.pathname === link.href || router.asPath === link.href
return (
<li
className='cursor-pointer list-none items-center flex mx-2 font-semibold'
onMouseOver={() => changeShow(true)}
onMouseOut={() => changeShow(false)}>
{!hasSubMenu && (
<div
className={
'px-2 h-full whitespace-nowrap duration-300 text-sm justify-between dark:text-gray-300 cursor-pointer flex flex-nowrap items-center ' +
(selected
? 'bg-green-600 text-white hover:text-white'
: 'hover:text-green-600')
}>
<SmartLink href={link?.href} target={link?.target}>
{link?.icon && <i className={link?.icon} />} {link?.name}
</SmartLink>
</div>
)}
{/* 包含子選單 */}
{hasSubMenu && (
<>
<div
className={
'px-2 h-full whitespace-nowrap duration-300 text-sm justify-between dark:text-gray-300 cursor-pointer flex flex-nowrap items-center ' +
(selected
? 'bg-green-600 text-white hover:text-white'
: 'hover:text-green-600')
}>
<div>
{link?.icon && <i className={link?.icon} />} {link?.name}
{hasSubMenu && (
<i
className={`px-2 fas fa-chevron-down duration-500 transition-all ${show ? ' rotate-180' : ''}`}></i>
)}
</div>
</div>
{/* 下拉選單內容 */}
<ul
className={`${show ? 'visible opacity-100 top-12 ' : 'invisible opacity-0 top-10 '} border-gray-100 bg-white dark:bg-black dark:border-gray-800 transition-all duration-300 z-20 absolute block drop-shadow-lg `}>
{link?.subMenus?.map((sLink, index) => {
return (
<li
key={index}
className='not:last-child:border-b-0 border-b text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-900 tracking-widest transition-all duration-200 dark:border-gray-800 py-3 pr-6 pl-3'>
<SmartLink href={sLink.href} target={link?.target}>
<span className='text-xs'>
{link?.icon && <i className={sLink?.icon}> &nbsp; </i>}
{sLink.title}
</span>
</SmartLink>
</li>
)
})}
</ul>
</>
)}
</li>
)
}

View File

@@ -1,29 +0,0 @@
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
export const NormalMenu = props => {
const { link } = props
const router = useRouter()
if (!link || !link.show) {
return null
}
const selected = router.pathname === link.href || router.asPath === link.href
return (
<SmartLink
key={link?.href}
title={link.name}
href={link.href}
className={
'py-0.5 duration-500 justify-between text-gray-500 dark:text-gray-300 hover:text-black hover:underline cursor-pointer flex flex-nowrap items-center ' +
(selected ? 'text-black' : ' ')
}>
<div className='my-auto items-center justify-center flex '>
<div className={'hover:text-black'}>{link.name}</div>
</div>
{link.slot}
</SmartLink>
)
}

View File

@@ -1,30 +0,0 @@
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
export const MenuItemPCNormal = props => {
const { link } = props
const router = useRouter()
const selected = router.pathname === link.href || router.asPath === link.href
if (!link || !link.show) {
return null
}
return (
<SmartLink
key={`${link.id}-${link.slug}`}
title={link.name}
href={link.href}
className={
'px-2 duration-300 text-sm justify-between dark:text-gray-300 cursor-pointer flex flex-nowrap items-center ' +
(selected
? 'bg-green-600 text-white hover:text-white'
: 'hover:text-green-600')
}>
<div className='items-center justify-center flex '>
<i className={link.icon} />
<div className='ml-2 whitespace-nowrap'>{link.name}</div>
</div>
{link.slot}
</SmartLink>
)
}

View File

@@ -1,90 +0,0 @@
import Badge from '@/components/Badge'
import Collapse from '@/components/Collapse'
import { siteConfig } from '@/lib/config'
import { useEffect, useState } from 'react'
import BlogPostCard from './BlogPostCard'
/**
* 導覽列表
* @param posts 所有文章
* @param tags 所有標籤
* @returns {JSX.Element}
* @constructor
*/
const NavPostItem = props => {
const { group, expanded, toggleItem } = props // 接收傳入的展開狀態與切換函式
const hoverExpand = siteConfig('GITBOOK_FOLDER_HOVER_EXPAND')
const [isTouchDevice, setIsTouchDevice] = useState(false)
// 偵測是否為觸控裝置
useEffect(() => {
const checkTouchDevice = () => {
if (window.matchMedia('(pointer: coarse)').matches) {
setIsTouchDevice(true)
}
}
checkTouchDevice()
// 選用:監聽視窗尺寸變化時重新檢測
window.addEventListener('resize', checkTouchDevice)
return () => {
window.removeEventListener('resize', checkTouchDevice)
}
}, [])
// 當展開狀態改變時觸發切換函式並同步內部狀態
const toggleOpenSubMenu = () => {
toggleItem() // 呼叫父元件傳入的切換函式
}
const onHoverToggle = () => {
// 允許滑鼠懸停時自動展開,而非點擊
if (!hoverExpand || isTouchDevice) {
return
}
toggleOpenSubMenu()
}
const groupHasLatest = group?.items?.some(post => post.isLatest)
if (group?.category) {
return (
<>
<div
onMouseEnter={onHoverToggle}
onClick={toggleOpenSubMenu}
className='cursor-pointer relative flex justify-between text-md p-2 hover:bg-gray-50 rounded-md dark:hover:bg-yellow-100 dark:hover:text-yellow-600'
key={group?.category}>
<span className={`${expanded && 'font-semibold'}`}>
{group?.category}
</span>
<div className='inline-flex items-center select-none pointer-events-none '>
<i
className={`px-2 fas fa-chevron-left transition-all opacity-50 duration-700 ${expanded ? '-rotate-90' : ''}`}></i>
</div>
{groupHasLatest &&
siteConfig('GITBOOK_LATEST_POST_RED_BADGE') &&
!expanded && <Badge />}
</div>
<Collapse isOpen={expanded} onHeightChange={props.onHeightChange}>
{group?.items?.map((post, index) => (
<div key={index} className='ml-3 border-l'>
<BlogPostCard className='ml-3' post={post} />
</div>
))}
</Collapse>
</>
)
} else {
return (
<>
{group?.items?.map((post, index) => (
<div key={index}>
<BlogPostCard className='text-md py-2' post={post} />
</div>
))}
</>
)
}
}
export default NavPostItem

View File

@@ -1,165 +0,0 @@
import { siteConfig } from '@/lib/config'
import { useGlobal } from '@/lib/global'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import CONFIG from '../config'
import BlogPostCard from './BlogPostCard'
import NavPostItem from './NavPostItem'
/**
* 部落格列表滾動分頁
* @param posts 所有文章
* @param tags 所有標籤
* @returns {JSX.Element}
* @constructor
*/
const NavPostList = props => {
const { filteredNavPages } = props
const { locale, currentSearch } = useGlobal()
const router = useRouter()
// 依分類將文章歸成資料夾
const categoryFolders = groupArticles(filteredNavPages)
// 存放被展開的群組
const [expandedGroups, setExpandedGroups] = useState([])
// 是否採用排他折疊,一次只展開一個資料夾
const GITBOOK_EXCLUSIVE_COLLAPSE = siteConfig(
'GITBOOK_EXCLUSIVE_COLLAPSE',
null,
CONFIG
)
useEffect(() => {
// 展開資料夾
setTimeout(() => {
const currentPath = decodeURIComponent(router.asPath.split('?')[0])
const defaultOpenIndex = getDefaultOpenIndexByPath(
categoryFolders,
currentPath
)
setExpandedGroups([defaultOpenIndex])
}, 500)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [router, filteredNavPages])
// 切換折疊項目,當陣列狀態改變時觸發
const toggleItem = index => {
let newExpandedGroups = [...expandedGroups] // 建立新的展開群組陣列
// 若 expandedGroups 中不存在則加入,存在則移除
if (expandedGroups.includes(index)) {
// 若 expandedGroups 中包含 index則移除
newExpandedGroups = newExpandedGroups.filter(
expandedIndex => expandedIndex !== index
)
} else {
// 若 expandedGroups 中不含 index則加入
newExpandedGroups.push(index)
}
// 是否排他
if (GITBOOK_EXCLUSIVE_COLLAPSE) {
// 若折疊選單為排他模式,僅保留目前群組其餘關閉
newExpandedGroups = newExpandedGroups.filter(
expandedIndex => expandedIndex === index
)
}
// 更新展開群組陣列
setExpandedGroups(newExpandedGroups)
}
// 無資料時
if (!categoryFolders || categoryFolders.length === 0) {
// 空白內容
return (
<div className='flex w-full items-center justify-center min-h-screen mx-auto md:-mt-20'>
<p className='text-gray-500 dark:text-gray-300'>
{locale.COMMON.NO_RESULTS_FOUND}{' '}
{currentSearch && <div>{currentSearch}</div>}
</p>
</div>
)
}
// 文章首頁對應路徑
const href = siteConfig('GITBOOK_INDEX_PAGE') + ''
const homePost = {
id: '-1',
title: siteConfig('DESCRIPTION'),
href: href.indexOf('/') !== 0 ? '/' + href : href
}
return (
<div
id='posts-wrapper'
className='w-full flex-grow space-y-0.5 pr-4 tracking-wider'>
{/* 當前文章 */}
<BlogPostCard className='mb-4' post={homePost} />
{/* 文章列表 */}
{categoryFolders?.map((group, index) => (
<NavPostItem
key={index}
group={group}
onHeightChange={props.onHeightChange}
expanded={expandedGroups.includes(index)} // 將展開狀態傳給子元件
toggleItem={() => toggleItem(index)} // 將切換函式傳給子元件
/>
))}
</div>
)
}
// 依分類將文章歸成資料夾
function groupArticles(filteredNavPages) {
if (!filteredNavPages) {
return []
}
const groups = []
const AUTO_SORT = siteConfig('GITBOOK_AUTO_SORT', true, CONFIG)
for (let i = 0; i < filteredNavPages.length; i++) {
const item = filteredNavPages[i]
const categoryName = item?.category ? item?.category : '' // 將 category 轉成字串
let existingGroup = null
// 啟用自動分組排序;會把相同分類歸到同一個資料夾,忽略 Notion 中的排序
if (AUTO_SORT) {
existingGroup = groups.find(group => group.category === categoryName) // 尋找同名的最後一個群組
} else {
existingGroup = groups[groups.length - 1] // 取得最後一個群組
}
// 新增資料
if (existingGroup && existingGroup.category === categoryName) {
existingGroup.items.push(item)
} else {
groups.push({ category: categoryName, items: [item] })
}
}
return groups
}
/**
* 查看當前路徑需要展開的選單索引
* 若皆不符合則回傳 0即預設展開第一個
* @param {*} categoryFolders
* @param {*} path
* @returns {number} 需展開的選單索引
*/
function getDefaultOpenIndexByPath(categoryFolders, path) {
// 找出符合條件的第一個索引
const index = categoryFolders.findIndex(group => {
return group.items.some(post => path === post.href)
})
// 若找到符合條件的索引則回傳
if (index !== -1) {
return index
}
return 0
}
export default NavPostList

View File

@@ -1,61 +0,0 @@
import { useGlobal } from '@/lib/global'
import { useGitBookGlobal } from '@/themes/gitbook'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import NavPostList from './NavPostList'
/**
* 懸浮抽屜 頁面內導覽
* @param toc
* @param post
* @returns {JSX.Element}
* @constructor
*/
const PageNavDrawer = props => {
const { pageNavVisible, changePageNavVisible } = useGitBookGlobal()
const { filteredNavPages } = props
const { locale } = useGlobal()
const router = useRouter()
const switchVisible = () => {
changePageNavVisible(!pageNavVisible)
}
useEffect(() => {
changePageNavVisible(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [router])
return (
<>
<div
id='gitbook-left-float'
className='fixed top-0 left-0 z-40 md:hidden'>
{/* 側邊選單 */}
<div
className={`${pageNavVisible ? 'animate__slideInLeft ' : '-ml-80 animate__slideOutLeft'}
overflow-y-hidden shadow-card w-72 duration-200 fixed left-1 bottom-16 rounded py-2 bg-white dark:bg-hexo-black-gray`}>
<div className='px-4 pb-2 flex justify-between items-center border-b font-bold'>
<span>{locale.COMMON.ARTICLE_LIST}</span>
<i
className='fas fa-times p-1 cursor-pointer'
onClick={() => {
changePageNavVisible(false)
}}></i>
</div>
{/* 所有文章列表 */}
<div className='dark:text-gray-400 text-gray-600 h-96 overflow-y-scroll p-3'>
<NavPostList filteredNavPages={filteredNavPages} />
</div>
</div>
</div>
{/* 背景遮罩 */}
<div
id='left-drawer-background'
className={`${pageNavVisible ? 'block' : 'hidden'} fixed top-0 left-0 z-30 w-full h-full`}
onClick={switchVisible}
/>
</>
)
}
export default PageNavDrawer

View File

@@ -1,54 +0,0 @@
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
import { useGlobal } from '@/lib/global'
/**
* 簡易翻頁外掛
* @param page 當前頁碼
* @param totalPage 是否有下一頁
* @returns {JSX.Element}
* @constructor
*/
const PaginationSimple = ({ page, totalPage }) => {
const { locale } = useGlobal()
const router = useRouter()
const currentPage = +page
const showNext = currentPage < totalPage
const pagePrefix = router.asPath.replace(/\/page\/[1-9]\d*/, '').replace(/\/$/, '')
return (
<div className="my-10 flex justify-between font-medium text-black dark:text-gray-100 space-x-2">
<SmartLink
href={{
pathname:
currentPage === 2
? `${pagePrefix}/`
: `${pagePrefix}/page/${currentPage - 1}`,
query: router.query.s ? { s: router.query.s } : {}
}}
passHref
rel="prev"
className={`${
currentPage === 1 ? 'invisible' : 'block'
} text-center w-full duration-200 px-4 py-2 hover:border-green-500 border-b-2 hover:font-bold`}>
{locale.PAGINATION.PREV}
</SmartLink>
<SmartLink
href={{
pathname: `${pagePrefix}/page/${currentPage + 1}`,
query: router.query.s ? { s: router.query.s } : {}
}}
passHref
rel="next"
className={`${
+showNext ? 'block' : 'invisible'
} text-center w-full duration-200 px-4 py-2 hover:border-green-500 border-b-2 hover:font-bold`}>
{locale.PAGINATION.NEXT}
</SmartLink>
</div>
)
}
export default PaginationSimple

View File

@@ -1,44 +0,0 @@
import { useEffect, useState } from 'react'
import { isBrowser } from '@/lib/utils'
/**
* 頂部頁面閱讀進度條
* @returns {JSX.Element}
* @constructor
*/
const Progress = ({ targetRef, showPercent = true }) => {
const currentRef = targetRef?.current || targetRef
const [percent, changePercent] = useState(0)
const scrollListener = () => {
const target = currentRef || (isBrowser && document.getElementById('posts-wrapper'))
if (target) {
const clientHeight = target.clientHeight
const scrollY = window.pageYOffset
const fullHeight = clientHeight - window.outerHeight
let per = parseFloat(((scrollY / fullHeight) * 100).toFixed(0))
if (per > 100) per = 100
if (per < 0) per = 0
changePercent(per)
}
}
useEffect(() => {
document.addEventListener('scroll', scrollListener)
return () => document.removeEventListener('scroll', scrollListener)
}, [])
return (
<div className="h-4 w-full shadow-2xl bg-hexo-light-gray dark:bg-black">
<div
className="h-4 bg-gray-600 duration-200"
style={{ width: `${percent}%` }}
>
{showPercent && (
<div className="text-right text-white text-xs">{percent}%</div>
)}
</div>
</div>
)
}
export default Progress

View File

@@ -1,36 +0,0 @@
import { useEffect, useState } from 'react'
export default function RevolverMaps () {
const [load, changeLoad] = useState(false)
useEffect(() => {
if (!load) {
initRevolverMaps()
changeLoad(true)
}
}, [])
return <div id="revolvermaps" className='p-4'/>
}
function initRevolverMaps () {
if (screen.width >= 768) {
Promise.all([
loadExternalResource('https://rf.revolvermaps.com/0/0/8.js?i=5jnp1havmh9&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33')
]).then(() => {
console.log('地圖載入完成')
})
}
}
// 封裝非同步載入資源的方法
function loadExternalResource (url) {
return new Promise((resolve, reject) => {
const container = document.getElementById('revolvermaps')
const tag = document.createElement('script')
tag.src = url
if (tag) {
tag.onload = () => resolve(url)
tag.onerror = () => reject(url)
container.appendChild(tag)
}
})
}

View File

@@ -1,159 +0,0 @@
import { siteConfig } from '@/lib/config'
import { deepClone } from '@/lib/utils'
import { useGitBookGlobal } from '@/themes/gitbook'
import { useImperativeHandle, useRef, useState } from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
let lock = false
/**
* 搜尋列
*/
const SearchInput = ({ currentSearch, cRef, className }) => {
const searchInputRef = useRef()
const { searchModal, setFilteredNavPages, allNavPages } = useGitBookGlobal()
useImperativeHandle(cRef, () => {
return {
focus: () => {
searchInputRef?.current?.focus()
}
}
})
/**
* 快捷鍵設定
*/
useHotkeys('ctrl+k', e => {
searchInputRef?.current?.focus()
e.preventDefault()
handleSearch()
})
const handleSearch = () => {
// 使用 Algolia
if (siteConfig('ALGOLIA_APP_ID')) {
searchModal?.current?.openSearch()
}
let keyword = searchInputRef.current.value
if (keyword) {
keyword = keyword.trim()
} else {
setFilteredNavPages(allNavPages)
return
}
const filterAllNavPages = deepClone(allNavPages)
for (let i = filterAllNavPages.length - 1; i >= 0; i--) {
const post = filterAllNavPages[i]
const articleInfo = post.title + ''
const hit = articleInfo.toLowerCase().indexOf(keyword.toLowerCase()) > -1
if (!hit) {
// 刪除
filterAllNavPages.splice(i, 1)
}
}
// 更新完成
setFilteredNavPages(filterAllNavPages)
}
/**
* Enter 鍵
* @param {*} e
*/
const handleKeyUp = e => {
// 使用 Algolia
if (siteConfig('ALGOLIA_APP_ID')) {
searchModal?.current?.openSearch()
return
}
if (e.keyCode === 13) {
// Enter
handleSearch(searchInputRef.current.value)
} else if (e.keyCode === 27) {
// ESC
cleanSearch()
}
}
const handleFocus = () => {
// 使用 Algolia
if (siteConfig('ALGOLIA_APP_ID')) {
searchModal?.current?.openSearch()
}
}
/**
* 清除搜尋
*/
const cleanSearch = () => {
searchInputRef.current.value = ''
handleSearch()
setShowClean(false)
}
const [showClean, setShowClean] = useState(false)
const updateSearchKey = val => {
if (lock) {
return
}
searchInputRef.current.value = val
if (val) {
setShowClean(true)
} else {
setShowClean(false)
}
}
function lockSearchInput() {
lock = true
}
function unLockSearchInput() {
lock = false
}
return (
<div className={`${className} relative`}>
<div
className='absolute left-0 ml-4 items-center justify-center py-2'
onClick={handleSearch}>
<i
className={
'hover:text-black transform duration-200 text-gray-500 dark:hover:text-gray-300 cursor-pointer fas fa-search'
}
/>
</div>
<input
ref={searchInputRef}
type='text'
className={`rounded-lg border dark:border-black pl-12 leading-10 placeholder-gray-500 outline-none w-full transition focus:shadow-lg text-black bg-gray-100 dark:bg-black dark:text-white`}
onFocus={handleFocus}
onKeyUp={handleKeyUp}
placeholder='Search'
onCompositionStart={lockSearchInput}
onCompositionUpdate={lockSearchInput}
onCompositionEnd={unLockSearchInput}
onChange={e => updateSearchKey(e.target.value)}
defaultValue={currentSearch}
/>
<div
className='absolute right-0 mr-4 items-center justify-center py-2 text-gray-400 dark:text-gray-600'
onClick={handleSearch}>
Ctrl+K
</div>
{showClean && (
<div className='-ml-12 cursor-pointer flex float-right items-center justify-center py-2'>
<i
className='fas fa-times hover:text-black transform duration-200 text-gray-400 cursor-pointer dark:hover:text-gray-300'
onClick={cleanSearch}
/>
</div>
)}
</div>
)
}
export default SearchInput

View File

@@ -1,188 +0,0 @@
import QrCode from '@/components/QrCode'
import { siteConfig } from '@/lib/config'
import { useRef, useState } from 'react'
import { handleEmailClick } from '@/lib/plugins/mailEncrypt'
/**
* 社群聯絡按鈕組
* @returns {JSX.Element}
* @constructor
*/
const SocialButton = () => {
const CONTACT_GITHUB = siteConfig('CONTACT_GITHUB')
const CONTACT_TWITTER = siteConfig('CONTACT_TWITTER')
const CONTACT_TELEGRAM = siteConfig('CONTACT_TELEGRAM')
const CONTACT_LINKEDIN = siteConfig('CONTACT_LINKEDIN')
const CONTACT_WEIBO = siteConfig('CONTACT_WEIBO')
const CONTACT_INSTAGRAM = siteConfig('CONTACT_INSTAGRAM')
const CONTACT_EMAIL = siteConfig('CONTACT_EMAIL')
const ENABLE_RSS = siteConfig('ENABLE_RSS')
const CONTACT_BILIBILI = siteConfig('CONTACT_BILIBILI')
const CONTACT_YOUTUBE = siteConfig('CONTACT_YOUTUBE')
const CONTACT_XIAOHONGSHU = siteConfig('CONTACT_XIAOHONGSHU')
const CONTACT_ZHISHIXINGQIU = siteConfig('CONTACT_ZHISHIXINGQIU')
const CONTACT_WEHCHAT_PUBLIC = siteConfig('CONTACT_WEHCHAT_PUBLIC')
const [qrCodeShow, setQrCodeShow] = useState(false)
const openPopover = () => {
setQrCodeShow(true)
}
const closePopover = () => {
setQrCodeShow(false)
}
const emailIcon = useRef(null)
return (
<div className='w-full justify-center flex-wrap flex'>
<div className='space-x-3 text-xl flex items-center text-gray-600 dark:text-gray-300 '>
{CONTACT_GITHUB && (
<a
target='_blank'
rel='noreferrer'
title={'github'}
href={CONTACT_GITHUB}>
<i className='transform hover:scale-125 duration-150 fab fa-github dark:hover:text-green-400 hover:text-green-600' />
</a>
)}
{CONTACT_TWITTER && (
<a
target='_blank'
rel='noreferrer'
title={'twitter'}
href={CONTACT_TWITTER}>
<i className='transform hover:scale-125 duration-150 fab fa-twitter dark:hover:text-green-400 hover:text-green-600' />
</a>
)}
{CONTACT_TELEGRAM && (
<a
target='_blank'
rel='noreferrer'
href={CONTACT_TELEGRAM}
title={'telegram'}>
<i className='transform hover:scale-125 duration-150 fab fa-telegram dark:hover:text-green-400 hover:text-green-600' />
</a>
)}
{CONTACT_LINKEDIN && (
<a
target='_blank'
rel='noreferrer'
href={CONTACT_LINKEDIN}
title={'linkIn'}>
<i className='transform hover:scale-125 duration-150 fab fa-linkedin dark:hover:text-green-400 hover:text-green-600' />
</a>
)}
{CONTACT_WEIBO && (
<a
target='_blank'
rel='noreferrer'
title={'weibo'}
href={CONTACT_WEIBO}>
<i className='transform hover:scale-125 duration-150 fab fa-weibo dark:hover:text-green-400 hover:text-green-600' />
</a>
)}
{CONTACT_INSTAGRAM && (
<a
target='_blank'
rel='noreferrer'
title={'instagram'}
href={CONTACT_INSTAGRAM}>
<i className='transform hover:scale-125 duration-150 fab fa-instagram dark:hover:text-green-400 hover:text-green-600' />
</a>
)}
{CONTACT_EMAIL && (
<a
onClick={e => handleEmailClick(e, emailIcon, CONTACT_EMAIL)}
title='email'
className='cursor-pointer'
ref={emailIcon}>
<i className='transform hover:scale-125 duration-150 fas fa-envelope dark:hover:text-green-400 hover:text-green-600' />
</a>
)}
{ENABLE_RSS && (
<a
target='_blank'
rel='noreferrer'
title={'RSS'}
href={'/rss/feed.xml'}>
<i className='transform hover:scale-125 duration-150 fas fa-rss dark:hover:text-green-400 hover:text-green-600' />
</a>
)}
{CONTACT_BILIBILI && (
<a
target='_blank'
rel='noreferrer'
title={'bilibili'}
href={CONTACT_BILIBILI}>
<i className='transform hover:scale-125 duration-150 dark:hover:text-green-400 hover:text-green-600 fab fa-bilibili' />
</a>
)}
{CONTACT_YOUTUBE && (
<a
target='_blank'
rel='noreferrer'
title={'youtube'}
href={CONTACT_YOUTUBE}>
<i className='transform hover:scale-125 duration-150 fab fa-youtube dark:hover:text-green-400 hover:text-green-600' />
</a>
)}
{CONTACT_XIAOHONGSHU && (
<a
target='_blank'
rel='noreferrer'
title={'小紅書'}
href={CONTACT_XIAOHONGSHU}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className='transform hover:scale-125 duration-150 w-6'
src='/svg/xiaohongshu.svg'
alt='小紅書'
/>
</a>
)}
{CONTACT_ZHISHIXINGQIU && (
<a
target='_blank'
rel='noreferrer'
title={'知識星球'}
className='flex justify-center items-center'
href={CONTACT_ZHISHIXINGQIU}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className='transform hover:scale-125 duration-150 w-6'
src='/svg/zhishixingqiu.svg'
alt='知識星球'
/>{' '}
</a>
)}
{CONTACT_WEHCHAT_PUBLIC && (
<button
onMouseEnter={openPopover}
onMouseLeave={closePopover}
aria-label={'微信公眾號'}>
<div id='wechat-button'>
<i className='transform scale-105 hover:scale-125 duration-150 fab fa-weixin dark:hover:text-green-400 hover:text-green-600' />
</div>
{/* QR Code 彈窗 */}
<div className='absolute'>
<div
id='pop'
className={
(qrCodeShow ? 'opacity-100 ' : ' invisible opacity-0') +
' z-40 absolute bottom-10 -left-10 bg-white shadow-xl transition-all duration-200 text-center'
}>
<div className='p-2 mt-1 w-28 h-28'>
{qrCodeShow && <QrCode value={CONTACT_WEHCHAT_PUBLIC} />}
</div>
</div>
</div>
</button>
)}
</div>
</div>
)
}
export default SocialButton

View File

@@ -1,27 +0,0 @@
import TagItemMini from './TagItemMini'
/**
* 標籤組
* @param tags
* @param currentTag
* @returns {JSX.Element}
* @constructor
*/
const TagGroups = ({ tagOptions, currentTag }) => {
if (!tagOptions) return <></>
return (
<div id='tags-group' className='dark:border-gray-600 py-4'>
<div className='mb-2'><i className='mr-2 fas fa-tag' />標籤</div>
<div className='space-y-2'>
{
tagOptions?.map(tag => {
const selected = tag.name === currentTag
return <TagItemMini key={tag.name} tag={tag} selected={selected} />
})
}
</div>
</div>
)
}
export default TagGroups

View File

@@ -1,21 +0,0 @@
import SmartLink from '@/components/SmartLink'
const TagItemMini = ({ tag, selected = false }) => {
return (
<SmartLink
key={tag}
href={selected ? '/' : `/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
${selected
? 'text-white dark:text-gray-300 bg-black dark:bg-black dark:hover:bg-gray-900'
: `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'>{selected && <i className='mr-1 fas fa-tag'/>} {tag.name + (tag.count ? `(${tag.count})` : '')} </div>
</SmartLink>
)
}
export default TagItemMini

View File

@@ -1,25 +0,0 @@
const CONFIG = {
GITBOOK_INDEX_PAGE: 'about', // 文件首頁顯示的文章,請確認此路徑包含在您的 Notion 資料庫中
GITBOOK_AUTO_SORT: process.env.NEXT_PUBLIC_GITBOOK_AUTO_SORT || true, // 是否自動依分類名稱分組排序文章;自動分組可能會打亂您在 Notion 中的文章順序
GITBOOK_LATEST_POST_RED_BADGE:
process.env.NEXT_PUBLIC_GITBOOK_LATEST_POST_RED_BADGE || true, // 是否替最新文章顯示紅點
// 選單
GITBOOK_MENU_CATEGORY: true, // 顯示分類
GITBOOK_BOOK_MENU_TAG: true, // 顯示標籤
GITBOOK_MENU_ARCHIVE: true, // 顯示歸檔
GITBOOK_MENU_SEARCH: true, // 顯示搜尋
// 導覽文章自動排他折疊
GITBOOK_EXCLUSIVE_COLLAPSE: true, // 一次只展開一個分類,其它資料夾自動關閉。
GITBOOK_FOLDER_HOVER_EXPAND: false, // 左側導覽資料夾滑鼠懸停時自動展開;若為 false 則需點擊才會展開
// Widget
GITBOOK_WIDGET_REVOLVER_MAPS:
process.env.NEXT_PUBLIC_WIDGET_REVOLVER_MAPS || 'false', // 地圖外掛
GITBOOK_WIDGET_TO_TOP: true // 回到頂端按鈕
}
export default CONFIG

View File

@@ -1,14 +0,0 @@
export { LayoutBase, useGitBookGlobal } from './layouts/BaseLayout'
export {
LayoutDashboard,
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 { LayoutSignIn, LayoutSignUp } from './layouts/AuthLayouts'
export { default as CONFIG } from './config'
export { default as THEME_CONFIG } from './config'

View File

@@ -1,27 +0,0 @@
'use client'
import BlogArchiveItem from '../components/BlogArchiveItem'
/**
* 歸檔頁面
* 主要依靠頁面導覽
*/
const LayoutArchive = props => {
const { archivePosts } = props
return (
<>
<div className='mb-10 pb-20 md:py-12 py-3 min-h-full'>
{Object.keys(archivePosts)?.map(archiveTitle => (
<BlogArchiveItem
key={archiveTitle}
archiveTitle={archiveTitle}
archivePosts={archivePosts}
/>
))}
</div>
</>
)
}
export { LayoutArchive }

View File

@@ -1,54 +0,0 @@
'use client'
import NotionPage from '@/components/NotionPage'
import { SignIn, SignUp } from '@clerk/nextjs'
/**
* 登入頁面
*/
const LayoutSignIn = props => {
const { post } = props
const enableClerk = process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
return (
<>
<div className='grow mt-20'>
{/* Clerk 預設表單 */}
{enableClerk && (
<div className='flex justify-center py-6'>
<SignIn />
</div>
)}
<div id='article-wrapper'>
<NotionPage post={post} />
</div>
</div>
</>
)
}
/**
* 註冊頁面
*/
const LayoutSignUp = props => {
const { post } = props
const enableClerk = process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
return (
<>
<div className='grow mt-20'>
{/* Clerk 預設表單 */}
{enableClerk && (
<div className='flex justify-center py-6'>
<SignUp />
</div>
)}
<div id='article-wrapper'>
<NotionPage post={post} />
</div>
</div>
</>
)
}
export { LayoutSignIn, LayoutSignUp }

View File

@@ -1,223 +0,0 @@
'use client'
import { AdSlot } from '@/components/GoogleAdsense'
import Live2D from '@/components/Live2D'
import LoadingCover from '@/components/LoadingCover'
import dynamic from 'next/dynamic'
import { createContext, useContext, useEffect, useRef, useState } from 'react'
import { siteConfig } from '@/lib/config'
import { useGlobal } from '@/lib/global'
import { useRouter } from 'next/router'
import { getShortId } from '@/lib/utils/pageId'
import Announcement from '../components/Announcement'
import ArticleInfo from '../components/ArticleInfo'
import BottomMenuBar from '../components/BottomMenuBar'
import Catalog from '../components/Catalog'
import Footer from '../components/Footer'
import Header from '../components/Header'
import InfoCard from '../components/InfoCard'
import JumpToTopButton from '../components/JumpToTopButton'
import NavPostList from '../components/NavPostList'
import PageNavDrawer from '../components/PageNavDrawer'
import RevolverMaps from '../components/RevolverMaps'
import CONFIG from '../config'
import { Style } from '../style'
const AlgoliaSearchModal = dynamic(
() => import('@/components/AlgoliaSearchModal'),
{ ssr: false }
)
const WWAds = dynamic(() => import('@/components/WWAds'), { ssr: false })
// 主題全域變數
const ThemeGlobalGitbook = createContext()
const useGitBookGlobal = () => useContext(ThemeGlobalGitbook)
/**
* 為最新文章加入紅點標記
*/
function getNavPagesWithLatest(allNavPages, latestPosts, post) {
// localStorage 儲存 id 與上次閱讀時間戳: posts_read_time = {"${post.id}":"Date()"}
const postReadTime = JSON.parse(
localStorage.getItem('post_read_time') || '{}'
)
if (post) {
postReadTime[getShortId(post.id)] = new Date().getTime()
}
// 更新記錄
localStorage.setItem('post_read_time', JSON.stringify(postReadTime))
return allNavPages?.map(item => {
const res = {
short_id: item.short_id,
title: item.title || '',
pageCoverThumbnail: item.pageCoverThumbnail || '',
category: item.category || null,
tags: item.tags || null,
summary: item.summary || null,
slug: item.slug,
href: item.href,
pageIcon: item.pageIcon || '',
lastEditedDate: item.lastEditedDate
}
// 屬於最新的文章通常 6 篇 &&(無閱讀紀錄 || 最近更新時間大於上次閱讀時間)
if (
latestPosts.some(post => post?.id.indexOf(item?.short_id) === 14) &&
(!postReadTime[item.short_id] ||
postReadTime[item.short_id] < new Date(item.lastEditedDate).getTime())
) {
return { ...res, isLatest: true }
} else {
return res
}
})
}
/**
* 基礎佈局
* 左右雙欄,手機版改為頂部導覽列
*/
const LayoutBase = props => {
const {
children,
post,
allNavPages,
latestPosts,
slotLeft,
slotRight,
slotTop
} = props
const { fullWidth } = useGlobal()
const router = useRouter()
const [tocVisible, changeTocVisible] = useState(false)
const [pageNavVisible, changePageNavVisible] = useState(false)
const [filteredNavPages, setFilteredNavPages] = useState(allNavPages)
const searchModal = useRef(null)
useEffect(() => {
setFilteredNavPages(getNavPagesWithLatest(allNavPages, latestPosts, post))
}, [router])
const GITBOOK_LOADING_COVER = siteConfig(
'GITBOOK_LOADING_COVER',
true,
CONFIG
)
return (
<ThemeGlobalGitbook.Provider
value={{
searchModal,
tocVisible,
changeTocVisible,
filteredNavPages,
setFilteredNavPages,
allNavPages,
pageNavVisible,
changePageNavVisible
}}>
<Style />
<div
id='theme-gitbook'
className={`${siteConfig('FONT_STYLE')} pb-16 md:pb-0 scroll-smooth bg-white dark:bg-black w-full h-full min-h-screen justify-center dark:text-gray-300`}>
<AlgoliaSearchModal cRef={searchModal} {...props} />
{/* 頂部導覽列 */}
<Header {...props} />
<main
id='wrapper'
className={`${siteConfig('LAYOUT_SIDEBAR_REVERSE') ? 'flex-row-reverse' : ''} relative flex justify-between w-full gap-x-6 h-full mx-auto max-w-screen-4xl`}>
{/* 左側抽屜 */}
{fullWidth ? null : (
<div className={'hidden md:block relative z-10 '}>
<div className='w-80 pt-14 pb-4 sticky top-0 h-screen flex justify-between flex-col'>
{/* 導覽清單 */}
<div className='overflow-y-scroll scroll-hidden pt-10 pl-5'>
{/* 嵌入區塊 */}
{slotLeft}
{/* 文章列表 */}
<NavPostList filteredNavPages={filteredNavPages} {...props} />
</div>
{/* 頁尾 */}
<Footer {...props} />
</div>
</div>
)}
{/* 內容區域 */}
<div
id='center-wrapper'
className='flex flex-col justify-between w-full relative z-10 pt-14 min-h-screen'>
<div
id='container-inner'
className={`w-full ${fullWidth ? 'px-5' : 'max-w-3xl px-3 lg:px-0'} justify-center mx-auto`}>
{slotTop}
<WWAds className='w-full' orientation='horizontal' />
{children}
{/* Google 廣告 */}
<AdSlot type='in-article' />
<WWAds className='w-full' orientation='horizontal' />
</div>
{/* 手機版頁尾 */}
<div className='md:hidden'>
<Footer {...props} />
</div>
</div>
{/* 右側資訊欄 */}
{fullWidth ? null : (
<div
className={
'w-72 hidden 2xl:block dark:border-transparent flex-shrink-0 relative z-10 '
}>
<div className='py-14 sticky top-0'>
<ArticleInfo post={props?.post ? props?.post : props.notice} />
<div>
{/* 桌面版目錄 */}
<Catalog {...props} />
{slotRight}
{router.route === '/' && (
<>
<InfoCard {...props} />
{siteConfig(
'GITBOOK_WIDGET_REVOLVER_MAPS',
null,
CONFIG
) === 'true' && <RevolverMaps />}
<Live2D />
</>
)}
{/* 主題首頁僅顯示公告 */}
<Announcement {...props} />
</div>
<AdSlot type='in-article' />
<Live2D />
</div>
</div>
)}
</main>
{GITBOOK_LOADING_COVER && <LoadingCover />}
{/* 回頂按鈕 */}
<JumpToTopButton />
{/* 手機版導覽抽屜 */}
<PageNavDrawer {...props} filteredNavPages={filteredNavPages} />
{/* 手機版底部導覽列 */}
<BottomMenuBar {...props} />
</div>
</ThemeGlobalGitbook.Provider>
)
}
export { LayoutBase, useGitBookGlobal }

View File

@@ -1,101 +0,0 @@
'use client'
import NotionPage from '@/components/NotionPage'
import { siteConfig } from '@/lib/config'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import DashboardBody from '../components/ui/dashboard/DashboardBody'
import DashboardHeader from '../components/ui/dashboard/DashboardHeader'
import CONFIG from '../config'
/**
* 首頁
* 重新導向到指定的文章詳情頁
*/
const LayoutIndex = props => {
const router = useRouter()
const index = siteConfig('GITBOOK_INDEX_PAGE', 'about', CONFIG)
const [hasRedirected, setHasRedirected] = useState(false) // 用來追蹤是否已重新導向
useEffect(() => {
const tryRedirect = async () => {
if (!hasRedirected) {
// 僅在尚未導向時執行
setHasRedirected(true)
// 重新導向至指定文章
await router.push(index)
// 使用 setTimeout 檢查頁面載入狀態
setTimeout(() => {
const article = document.querySelector(
'#article-wrapper #notion-article'
)
if (!article) {
console.log('請檢查您的 Notion 資料庫中是否包含此 slug 頁面: ', index)
// 顯示錯誤訊息
const containerInner = document.querySelector(
'#theme-gitbook #container-inner'
)
const newHTML = `<h1 class="text-3xl pt-12 dark:text-gray-300">設定錯誤</h1><blockquote class="notion-quote notion-block-ce76391f3f2842d386468ff1eb705b92"><div>請在您的 Notion 中新增一篇 slug 為 ${index} 的文章</div></blockquote>`
containerInner?.insertAdjacentHTML('afterbegin', newHTML)
}
}, 2000)
}
}
if (index) {
console.log('重新導向', index)
tryRedirect()
} else {
console.log('未重新導向', index)
}
}, [index, hasRedirected, router])
return null
}
/**
* 文章列表
* 主要依靠頁面導覽
*/
const LayoutPostList = () => {
return <></>
}
/**
* 文章搜尋頁
* 主要依靠頁面導覽
*/
const LayoutSearch = () => {
return <></>
}
/**
* 儀表板
*/
const LayoutDashboard = props => {
const { post } = props
return (
<>
<div className='container grow'>
<div className='flex flex-wrap justify-center -mx-4'>
<div id='container-inner' className='w-full p-4'>
{post && (
<div id='article-wrapper' className='mx-auto'>
<NotionPage {...props} />
</div>
)}
</div>
</div>
</div>
{/* 儀表板 */}
<DashboardHeader />
<DashboardBody />
</>
)
}
export { LayoutDashboard, LayoutIndex, LayoutPostList, LayoutSearch }

View File

@@ -1,43 +0,0 @@
'use client'
import { useGlobal } from '@/lib/global'
import { isBrowser } from '@/lib/utils'
import { useEffect } from 'react'
import { useRouter } from 'next/router'
/**
* 404 頁面
*/
const Layout404 = () => {
const router = useRouter()
const { locale } = useGlobal()
useEffect(() => {
// 延遲 3 秒若載入失敗就返回首頁
setTimeout(() => {
const article = isBrowser && document.getElementById('article-wrapper')
if (!article) {
router.push('/').then(() => {
// console.log('找不到頁面', router.asPath)
})
}
}, 3000)
}, [router])
return (
<>
<div className='md:-mt-20 text-black w-full h-screen text-center justify-center content-center items-center flex flex-col'>
<div className='dark:text-gray-200'>
<h2 className='inline-block border-r-2 border-gray-600 mr-2 px-3 py-2 align-top'>
<i className='mr-2 fas fa-spinner animate-spin' />
404
</h2>
<div className='inline-block text-left h-32 leading-10 items-center'>
<h2 className='m-0 p-0'>{locale.NAV.PAGE_NOT_FOUND_REDIRECT}</h2>
</div>
</div>
</div>
</>
)
}
export { Layout404 }

View File

@@ -1,111 +0,0 @@
'use client'
import Comment from '@/components/Comment'
import NotionIcon from '@/components/NotionIcon'
import NotionPage from '@/components/NotionPage'
import ShareBar from '@/components/ShareBar'
import { siteConfig } from '@/lib/config'
import { isBrowser } from '@/lib/utils'
import Head from 'next/head'
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import CategoryItem from '../components/CategoryItem'
import { ArticleLock } from '../components/ArticleLock'
import ArticleAround from '../components/ArticleAround'
import CatalogDrawerWrapper from '../components/CatalogDrawerWrapper'
import TagItemMini from '../components/TagItemMini'
import CONFIG from '../config'
/**
* 文章詳情頁
*/
const LayoutSlug = props => {
const { post, prev, next, siteInfo, lock, validPassword } = props
const router = useRouter()
// 若為文件首頁文章則更新瀏覽器標題
const index = siteConfig('GITBOOK_INDEX_PAGE', 'about', CONFIG)
const basePath = router.asPath.split('?')[0]
const title =
basePath?.indexOf(index) > 0
? `${post?.title} | ${siteInfo?.description}`
: `${post?.title} | ${siteInfo?.title}`
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, router, waiting404])
return (
<>
<Head>
<title>{title}</title>
</Head>
{/* 文章加鎖 */}
{lock && <ArticleLock validPassword={validPassword} />}
{!lock && (
<div id='container'>
{/* 標題 */}
<h1 className='text-3xl pt-12 dark:text-gray-300'>
{siteConfig('POST_TITLE_ICON') && (
<NotionIcon icon={post?.pageIcon} />
)}
{post?.title}
</h1>
{/* Notion 文章主體 */}
{post && (
<section className='px-1'>
<div id='article-wrapper'>
<NotionPage post={post} />
</div>
{/* 分享 */}
<ShareBar post={post} />
{/* 文章分類與標籤資訊 */}
<div className='flex justify-between'>
{siteConfig('POST_DETAIL_CATEGORY') && post?.category && (
<CategoryItem category={post.category} />
)}
<div>
{siteConfig('POST_DETAIL_TAG') &&
post?.tagItems?.map(tag => (
<TagItemMini key={tag.name} tag={tag} />
))}
</div>
</div>
{post?.type === 'Post' && (
<ArticleAround prev={prev} next={next} />
)}
{/* <AdSlot />
<WWAds className='w-full' orientation='horizontal' /> */}
<Comment frontMatter={post} />
</section>
)}
{/* 文章目錄 */}
<CatalogDrawerWrapper {...props} />
</div>
)}
</>
)
}
export { LayoutSlug }

View File

@@ -1,72 +0,0 @@
'use client'
import SmartLink from '@/components/SmartLink'
import { useGlobal } from '@/lib/global'
import TagItemMini from '../components/TagItemMini'
/**
* 分類列表
*/
const LayoutCategoryIndex = props => {
const { categoryOptions } = props
const { locale } = useGlobal()
return (
<>
<div className='bg-white dark:bg-gray-700 py-10'>
<div className='dark:text-gray-200 mb-5'>
<i className='mr-4 fas fa-th' />
{locale.COMMON.CATEGORY}:
</div>
<div id='category-list' className='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>
</div>
</>
)
}
/**
* 標籤列表
*/
const LayoutTagIndex = props => {
const { tagOptions } = props
const { locale } = useGlobal()
return (
<>
<div className='bg-white dark:bg-gray-700 py-10'>
<div className='dark:text-gray-200 mb-5'>
<i className='mr-4 fas fa-tag' />
{locale.COMMON.TAGS}:
</div>
<div id='tags-list' className='duration-200 flex flex-wrap'>
{tagOptions?.map(tag => {
return (
<div key={tag.name} className='p-2'>
<TagItemMini key={tag.name} tag={tag} />
</div>
)}
})}
</div>
</div>
</>
)
}
export { LayoutCategoryIndex, LayoutTagIndex }

View File

@@ -1,22 +0,0 @@
/* eslint-disable react/no-unknown-property */
/**
* 此處樣式僅對當前主題生效
* 此處不支援 tailwindCSS 的 @apply 語法
* @returns
*/
const Style = () => {
return (
<style jsx global>{`
// 底色
.dark body {
background-color: black;
}
.bottom-button-group {
box-shadow: 0px -3px 10px 0px rgba(0, 0, 0, 0.1);
}
`}</style>
)
}
export { Style }

View File

@@ -1,70 +0,0 @@
# 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,7 +1,7 @@
import SmartLink from '@/components/SmartLink' import SmartLink from '@/components/SmartLink'
/** /**
* 上一則與下一文章 * 上一篇、下一文章
* @param {prev,next} param0 * @param {prev,next} param0
* @returns * @returns
*/ */

View File

@@ -6,7 +6,7 @@ import { formatDateFmt } from '@/lib/utils/formatDate'
import NotionIcon from '@/components/NotionIcon' import NotionIcon from '@/components/NotionIcon'
/** /**
* 文章說明 * 文章描述
* @param {*} props * @param {*} props
* @returns * @returns
*/ */
@@ -27,7 +27,7 @@ export default function ArticleInfo(props) {
<header className='text-md text-[var(--primary-color)] dark:text-gray-300 flex-wrap flex items-center leading-6'> <header className='text-md text-[var(--primary-color)] dark:text-gray-300 flex-wrap flex items-center leading-6'>
<div className='space-x-2'> <div className='space-x-2'>
<span className='text-sm'> <span className='text-sm'>
<SmartLink <SmartLink
className='p-1 hover:text-red-400 transition-all duration-200' className='p-1 hover:text-red-400 transition-all duration-200'
href={`/archive#${formatDateFmt(post?.publishDate, 'yyyy-MM')}`}> href={`/archive#${formatDateFmt(post?.publishDate, 'yyyy-MM')}`}>

View File

@@ -5,7 +5,7 @@ import { useEffect, useRef } from 'react'
* 加密文章驗證元件 * 加密文章驗證元件
* @param {password, validPassword} props * @param {password, validPassword} props
* @param password 正確的密碼 * @param password 正確的密碼
* @param validPassword(bool) 回呼函式,驗證正確回呼參數為 true * @param validPassword(bool) 回呼函式,驗證成功時回傳 true
* @returns * @returns
*/ */
export default function ArticleLock (props) { export default function ArticleLock (props) {
@@ -24,7 +24,7 @@ export default function ArticleLock (props) {
} }
const passwordInputRef = useRef(null) const passwordInputRef = useRef(null)
useEffect(() => { useEffect(() => {
// 選密碼輸入框並將聚焦 // 選密碼輸入框並將聚焦
passwordInputRef.current.focus() passwordInputRef.current.focus()
}, []) }, [])
@@ -38,7 +38,7 @@ export default function ArticleLock (props) {
submitPassword() submitPassword()
} }
}} }}
ref={passwordInputRef} // 綁定 ref 到 passwordInputRef 變數 ref={passwordInputRef} // ref 綁定到 passwordInputRef 變數
className='outline-none w-full text-sm pl-5 rounded-l transition focus:shadow-lg font-light leading-10 text-black dark:bg-gray-500 bg-gray-50' className='outline-none w-full text-sm pl-5 rounded-l transition focus:shadow-lg font-light leading-10 text-black dark:bg-gray-500 bg-gray-50'
></input> ></input>
<div onClick={submitPassword} className="px-3 whitespace-nowrap cursor-pointer items-center justify-center py-2 rounded-r duration-300 bg-gray-300" > <div onClick={submitPassword} className="px-3 whitespace-nowrap cursor-pointer items-center justify-center py-2 rounded-r duration-300 bg-gray-300" >

View File

@@ -1,7 +1,7 @@
import SmartLink from '@/components/SmartLink' import SmartLink from '@/components/SmartLink'
/** /**
* 歸檔文章清單 * 歸檔分組文章
* @param {*} param0 * @param {*} param0
* @returns * @returns
*/ */

View File

@@ -49,7 +49,7 @@ export const BlogItem = props => {
<header className='text-md text-[var(--primary-color)] dark:text-gray-300 flex-wrap flex items-center leading-6'> <header className='text-md text-[var(--primary-color)] dark:text-gray-300 flex-wrap flex items-center leading-6'>
<div className='space-x-2'> <div className='space-x-2'>
<span className='text-sm'> <span className='text-sm'>
<SmartLink <SmartLink
className='p-1 hover:text-red-400 transition-all duration-200' className='p-1 hover:text-red-400 transition-all duration-200'
href={`/archive#${formatDateFmt(post?.publishDate, 'yyyy-MM')}`}> href={`/archive#${formatDateFmt(post?.publishDate, 'yyyy-MM')}`}>

View File

@@ -7,7 +7,7 @@ import CONFIG from '../config'
import { BlogItem } from './BlogItem' import { BlogItem } from './BlogItem'
/** /**
* 部落格文章列表 * 部落格列表
* @param {*} props * @param {*} props
* @returns * @returns
*/ */
@@ -19,7 +19,7 @@ export default function BlogListPage(props) {
const totalPage = Math.ceil(postCount / POSTS_PER_PAGE) const totalPage = Math.ceil(postCount / POSTS_PER_PAGE)
const currentPage = +page const currentPage = +page
// 部落格列表入廣告 // 部落格列表入廣告
const TYPOGRAPHY_POST_AD_ENABLE = siteConfig( const TYPOGRAPHY_POST_AD_ENABLE = siteConfig(
'TYPOGRAPHY_POST_AD_ENABLE', 'TYPOGRAPHY_POST_AD_ENABLE',
false, false,

View File

@@ -5,7 +5,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { BlogItem } from './BlogItem' import { BlogItem } from './BlogItem'
/** /**
* 動部落格列表 * 動部落格列表
* @param {*} props * @param {*} props
* @returns * @returns
*/ */

View File

@@ -1,7 +1,7 @@
import { useGlobal } from '@/lib/global' import { useGlobal } from '@/lib/global'
/** /**
* 文章列表上方區塊 * 文章列表上方嵌入區塊
* @param {*} props * @param {*} props
* @returns * @returns
*/ */

View File

@@ -23,7 +23,7 @@ const Catalog = ({ post }) => {
return return
} }
const throttleMs = 100 // 降低節流時間提高響應速度 const throttleMs = 100 // 降低節流時間提升反應速度
const actionSectionScrollSpy = throttle(() => { const actionSectionScrollSpy = throttle(() => {
const sections = document.getElementsByClassName('notion-h') const sections = document.getElementsByClassName('notion-h')
@@ -32,15 +32,15 @@ const Catalog = ({ post }) => {
let prevBBox = null let prevBBox = null
let currentSectionId = null let currentSectionId = null
// 先檢查前視窗中的所有標題 // 先檢查前視窗中的所有標題
for (let i = 0; i < sections.length; ++i) { for (let i = 0; i < sections.length; ++i) {
const section = sections[i] const section = sections[i]
if (!section || !(section instanceof Element)) continue if (!section || !(section instanceof Element)) continue
const bbox = section.getBoundingClientRect() const bbox = section.getBoundingClientRect()
const offset = 100 // 固定移量,避免計算不穩定 const offset = 100 // 固定移量,避免計算不穩定
// 如果標題在視窗上方或接近頂部,認為是當前標題 // 如果標題在視窗上方或接近頂部,視為目前標題
if (bbox.top - offset < 0) { if (bbox.top - offset < 0) {
currentSectionId = section.getAttribute('data-id') currentSectionId = section.getAttribute('data-id')
prevBBox = bbox prevBBox = bbox
@@ -50,7 +50,7 @@ const Catalog = ({ post }) => {
} }
} }
// 如果沒找到任何標題視窗上方,使用第一個標題 // 若沒有找到任何標題位於視窗上方,使用第一個標題
if (!currentSectionId && sections.length > 0) { if (!currentSectionId && sections.length > 0) {
currentSectionId = sections[0].getAttribute('data-id') currentSectionId = sections[0].getAttribute('data-id')
} }
@@ -71,22 +71,22 @@ const Catalog = ({ post }) => {
}, throttleMs) }, throttleMs)
const content = document.querySelector('#container-inner') const content = document.querySelector('#container-inner')
if (!content) return // 防止 content 不存在 if (!content) return // 避免 content 不存在
// 加滾動內容變化的監聽 // 加滾動內容變化的監聽
content.addEventListener('scroll', actionSectionScrollSpy) content.addEventListener('scroll', actionSectionScrollSpy)
// 初始執行一次 // 初始執行一次
setTimeout(() => { setTimeout(() => {
actionSectionScrollSpy() actionSectionScrollSpy()
}, 300) // 延遲執行確保 DOM 已完全載入 }, 300) // 延遲執行確保 DOM 已完全載入
return () => { return () => {
content?.removeEventListener('scroll', actionSectionScrollSpy) content?.removeEventListener('scroll', actionSectionScrollSpy)
} }
}, [post]) }, [post])
// 目錄就直接返回空 // 沒有目錄就直接回傳空值
if (!post || !post?.toc || post?.toc?.length < 1) { if (!post || !post?.toc || post?.toc?.length < 1) {
return <></> return <></>
} }

View File

@@ -3,7 +3,7 @@ import DarkModeButton from '@/components/DarkModeButton'
import { siteConfig } from '@/lib/config' import { siteConfig } from '@/lib/config'
/** /**
* 頁 * 頁
* @param {*} props * @param {*} props
* @returns * @returns
*/ */

View File

@@ -3,8 +3,8 @@ import { useEffect, useState } from 'react'
/** /**
* 跳轉到網頁頂部 * 跳轉到網頁頂部
* 當畫面下滑 500 像素後會出現此按鈕 * 當螢幕下滑 500 像素後會出現該控制項
* @param targetRef 連結高度的目標 html 元素 * @param targetRef 關聯高度的目標 HTML 標籤
* @param showPercent 是否顯示百分比 * @param showPercent 是否顯示百分比
* @returns {JSX.Element} * @returns {JSX.Element}
* @constructor * @constructor

View File

@@ -3,7 +3,7 @@ import SmartLink from '@/components/SmartLink'
import { useState } from 'react' import { useState } from 'react'
/** /**
* 收合選單 * 摺疊選單
* @param {*} param0 * @param {*} param0
* @returns * @returns
*/ */
@@ -64,7 +64,7 @@ export const MenuItemCollapse = props => {
)} )}
</div> </div>
{/* 收合子選單 */} {/* 摺疊子選單 */}
{hasSubMenu && ( {hasSubMenu && (
<Collapse isOpen={isOpen} onHeightChange={props.onHeightChange}> <Collapse isOpen={isOpen} onHeightChange={props.onHeightChange}>
{link.subMenus.map((sLink, index) => { {link.subMenus.map((sLink, index) => {

View File

@@ -49,7 +49,7 @@ export const MenuItemDrop = ({ link }) => {
)} )}
</div> </div>
{/* 子單 */} {/* 子單 */}
<ul <ul
className={`${show ? 'visible opacity-100' : 'invisible opacity-0'} absolute glassmorphism md:left-28 md:top-0 top-6 w-full border-gray-100 transition-all duration-300 z-20 block`}> className={`${show ? 'visible opacity-100' : 'invisible opacity-0'} absolute glassmorphism md:left-28 md:top-0 top-6 w-full border-gray-100 transition-all duration-300 z-20 block`}>
{link?.subMenus?.map((sLink, index) => { {link?.subMenus?.map((sLink, index) => {

View File

@@ -53,7 +53,7 @@ export const MenuList = ({ customNav, customMenu }) => {
links = links.concat(customNav) links = links.concat(customNav)
} }
// 如果 開啟自訂選單,則覆蓋 Page 生的選單 // 若啟用自訂選單,就覆寫 Page 生的選單
if (siteConfig('CUSTOM_MENU')) { if (siteConfig('CUSTOM_MENU')) {
links = customMenu links = customMenu
} }
@@ -70,7 +70,7 @@ export const MenuList = ({ customNav, customMenu }) => {
<MenuItemDrop key={index} link={link} /> <MenuItemDrop key={index} link={link} />
))} ))}
</div> </div>
{/* 行動小螢幕選單 - 水平排列 */} {/* 行動小螢幕選單 - 水平排列 */}
<div <div
id='nav-menu-mobile' id='nav-menu-mobile'
className='flex md:hidden my-auto justify-center space-x-4'> className='flex md:hidden my-auto justify-center space-x-4'>

View File

@@ -1,7 +1,7 @@
import { siteConfig } from '@/lib/config' import { siteConfig } from '@/lib/config'
/** /**
* 社聯絡方式按鈕組 * 社聯絡方式按鈕組
* @returns {JSX.Element} * @returns {JSX.Element}
* @constructor * @constructor
*/ */

View File

@@ -1,7 +1,7 @@
import { siteConfig } from '@/lib/config' import { siteConfig } from '@/lib/config'
/** /**
* 標題區塊 * 標題
* @param {*} props * @param {*} props
* @returns * @returns
*/ */

View File

@@ -2,7 +2,7 @@ import CONFIG from '../config'
import { siteConfig } from '@/lib/config' import { siteConfig } from '@/lib/config'
/** /**
* 網站上方提示 * 網站頂部提示
* @returns * @returns
*/ */
export default function TopBar (props) { export default function TopBar (props) {

View File

@@ -5,7 +5,7 @@ const CONFIG = {
TYPOGRAPHY_POST_AD_ENABLE: process.env.NEXT_PUBLIC_TYPOGRAPHY_POST_AD_ENABLE || false, // 文章列表是否插入廣告 TYPOGRAPHY_POST_AD_ENABLE: process.env.NEXT_PUBLIC_TYPOGRAPHY_POST_AD_ENABLE || false, // 文章列表是否插入廣告
TYPOGRAPHY_POST_COVER_ENABLE: process.env.NEXT_PUBLIC_TYPOGRAPHY_POST_COVER_ENABLE || false, // 是否示部落格封面 TYPOGRAPHY_POST_COVER_ENABLE: process.env.NEXT_PUBLIC_TYPOGRAPHY_POST_COVER_ENABLE || false, // 是否示部落格封面
TYPOGRAPHY_ARTICLE_RECOMMEND_POSTS: process.env.NEXT_PUBLIC_TYPOGRAPHY_ARTICLE_RECOMMEND_POSTS || true, // 文章詳情底部顯示推薦 TYPOGRAPHY_ARTICLE_RECOMMEND_POSTS: process.env.NEXT_PUBLIC_TYPOGRAPHY_ARTICLE_RECOMMEND_POSTS || true, // 文章詳情底部顯示推薦

View File

@@ -1,8 +1,372 @@
export { LayoutBase, useSimpleGlobal } from './layouts/BaseLayout' import { AdSlot } from '@/components/GoogleAdsense'
export { LayoutIndex, LayoutPostList, LayoutSearch } from './layouts/ListLayouts' import replaceSearchResult from '@/components/Mark'
export { LayoutArchive } from './layouts/ArchiveLayout' import NotionPage from '@/components/NotionPage'
export { LayoutSlug } from './layouts/SlugLayout' import { siteConfig } from '@/lib/config'
export { Layout404 } from './layouts/NotFoundLayout' import { useGlobal } from '@/lib/global'
export { LayoutCategoryIndex, LayoutTagIndex } from './layouts/TaxonomyLayouts' import { isBrowser } from '@/lib/utils'
export { default as CONFIG } from './config' import dynamic from 'next/dynamic'
export { default as THEME_CONFIG } from './config' 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 ? (
// 讀取時顯示 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
}

View File

@@ -1,25 +0,0 @@
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

@@ -1,79 +0,0 @@
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

@@ -1,39 +0,0 @@
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

@@ -1,34 +0,0 @@
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

@@ -1,58 +0,0 @@
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

@@ -1,46 +0,0 @@
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

@@ -1,6 +1,6 @@
/* eslint-disable react/no-unknown-property */ /* eslint-disable react/no-unknown-property */
/** /**
* 此處樣式只對當前主題生效 * 此處樣式僅對目前主題生效
* 此處不支援 tailwindCSS 的 @apply 語法 * 此處不支援 tailwindCSS 的 @apply 語法
* @returns * @returns
*/ */

View File

@@ -1,21 +0,0 @@
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 }