Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
actions-user committed Sep 19, 2024
2 parents 87cca4f + 8332e97 commit 1d060a9
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 52 deletions.
3 changes: 2 additions & 1 deletion components/OpenWrite.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,14 @@ const OpenWrite = () => {
return
}
if (isBrowser && blogId) {
toggleTocItems(true) // 禁止目录项的点击

// Check if the element with id 'read-more-wrap' already exists
const readMoreWrap = document.getElementById('read-more-wrap')

// Only load the script if the element doesn't exist
if (!readMoreWrap) {
loadOpenWrite()
toggleTocItems(true) // 禁止目录项的点击
}
}
})
Expand Down
10 changes: 10 additions & 0 deletions pages/[prefix]/[slug]/[...suffix].js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import BLOG from '@/blog.config'
import { siteConfig } from '@/lib/config'
import { getGlobalData, getPost, getPostBlocks } from '@/lib/db/getSiteData'
import { getPageTableOfContents } from '@/lib/notion/getPageTableOfContents'
import { uploadDataToAlgolia } from '@/lib/plugins/algolia'
import { checkSlugHasMorThanTwoSlash, getRecommendPost } from '@/lib/utils/post'
import { idToUuid } from 'notion-utils'
Expand Down Expand Up @@ -97,6 +98,15 @@ export async function getStaticProps({
if (!props?.post?.blockMap) {
props.post.blockMap = await getPostBlocks(props.post.id, from)
}

// 目录默认加载
if (props.post?.blockMap?.block) {
props.post.content = Object.keys(props.post.blockMap.block).filter(
key => props.post.blockMap.block[key]?.value?.parent_id === props.post.id
)
props.post.toc = getPageTableOfContents(props.post, props.post.blockMap)
}

// 生成全文索引 && JSON.parse(BLOG.ALGOLIA_RECREATE_DATA)
if (BLOG.ALGOLIA_APP_ID) {
uploadDataToAlgolia(props?.post)
Expand Down
10 changes: 10 additions & 0 deletions pages/[prefix]/[slug]/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import BLOG from '@/blog.config'
import { siteConfig } from '@/lib/config'
import { getGlobalData, getPost, getPostBlocks } from '@/lib/db/getSiteData'
import { getPageTableOfContents } from '@/lib/notion/getPageTableOfContents'
import { uploadDataToAlgolia } from '@/lib/plugins/algolia'
import { checkSlugHasOneSlash, getRecommendPost } from '@/lib/utils/post'
import { idToUuid } from 'notion-utils'
Expand Down Expand Up @@ -86,6 +87,15 @@ export async function getStaticProps({ params: { prefix, slug }, locale }) {
if (!props?.post?.blockMap) {
props.post.blockMap = await getPostBlocks(props.post.id, from)
}

// 目录默认加载
if (props.post?.blockMap?.block) {
props.post.content = Object.keys(props.post.blockMap.block).filter(
key => props.post.blockMap.block[key]?.value?.parent_id === props.post.id
)
props.post.toc = getPageTableOfContents(props.post, props.post.blockMap)
}

// 生成全文索引 && JSON.parse(BLOG.ALGOLIA_RECREATE_DATA)
if (BLOG.ALGOLIA_APP_ID) {
uploadDataToAlgolia(props?.post)
Expand Down
14 changes: 8 additions & 6 deletions pages/[prefix]/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,6 @@ const Slug = props => {
setLock(true)
} else {
setLock(false)
if (!lock && post?.blockMap?.block) {
post.content = Object.keys(post.blockMap.block).filter(
key => post.blockMap.block[key]?.value?.parent_id === post.id
)
post.toc = getPageTableOfContents(post, post.blockMap)
}
}

// 读取上次记录 自动提交密码
Expand Down Expand Up @@ -171,6 +165,14 @@ export async function getStaticProps({ params: { prefix }, locale }) {
props.post.blockMap = await getPostBlocks(props.post.id, from)
}

// 目录默认加载
if (props.post?.blockMap?.block) {
props.post.content = Object.keys(props.post.blockMap.block).filter(
key => props.post.blockMap.block[key]?.value?.parent_id === props.post.id
)
props.post.toc = getPageTableOfContents(props.post, props.post.blockMap)
}

// 生成全文索引 && process.env.npm_lifecycle_event === 'build' && JSON.parse(BLOG.ALGOLIA_RECREATE_DATA)
if (BLOG.ALGOLIA_APP_ID) {
uploadDataToAlgolia(props?.post)
Expand Down
76 changes: 39 additions & 37 deletions themes/magzine/components/Catalog.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import throttle from 'lodash.throttle'
import { uuidToId } from 'notion-utils'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import Progress from './Progress'

/**
Expand All @@ -9,7 +9,7 @@ import Progress from './Progress'
* @returns {JSX.Element}
* @constructor
*/
const Catalog = ({ toc, className }) => {
const Catalog = ({ post, toc, className }) => {
const tocIds = []

// 目录自动滚动
Expand All @@ -19,43 +19,45 @@ const Catalog = ({ toc, className }) => {

// 监听滚动事件
useEffect(() => {
window.addEventListener('scroll', actionSectionScrollSpy)
actionSectionScrollSpy()
if (toc && toc.length > 1) {
actionSectionScrollSpy()
window.addEventListener('scroll', actionSectionScrollSpy)
}
setTimeout(() => {
console.log('目录', post, toc)
}, 1000)
return () => {
window.removeEventListener('scroll', actionSectionScrollSpy)
}
}, [])

const throttleMs = 200
const actionSectionScrollSpy = useCallback(
throttle(() => {
const sections = document.getElementsByClassName('notion-h')
let prevBBox = null
let currentSectionId = activeSection
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
const actionSectionScrollSpy = throttle(() => {
const sections = document.getElementsByClassName('notion-h')
let prevBBox = null
let currentSectionId = activeSection
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')
}
setActiveSection(currentSectionId)
const index = tocIds.indexOf(currentSectionId) || 0
tRef?.current?.scrollTo({ top: 28 * index, behavior: 'smooth' })
console.log(tRef?.current)
}, throttleMs)
)
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 index = tocIds.indexOf(currentSectionId) || 0
tRef?.current?.scrollTo({ top: 28 * index, behavior: 'smooth' })
}, throttleMs)

// 无目录就直接返回空
if (!toc || toc.length < 1) {
Expand All @@ -68,24 +70,24 @@ const Catalog = ({ toc, className }) => {
<Progress />
</div>
<div
className='overflow-y-auto scroll-hidden lg:max-h-dvh max-h-44'
className='overflow-y-auto scroll-hidden lg:max-h-96 max-h-44'
ref={tRef}>
<nav className='h-full text-black'>
{toc.map(tocItem => {
<nav className='h-full text-black'>
{toc?.map(tocItem => {
const id = uuidToId(tocItem.id)
tocIds.push(id)
return (
<a
key={id}
href={`#${id}`}
className={`notion-table-of-contents-item duration-300 transform dark:text-gray-300
className={`notion-table-of-contents-item duration-300 transform dark:text-gray-400
notion-table-of-contents-item-indent-level-${tocItem.indentLevel} `}>
<span
style={{
display: 'inline-block',
marginLeft: tocItem.indentLevel * 16
}}
className={`truncate ${activeSection === id ? 'font-bold text-gray-500 underline' : ''}`}>
className={`truncate ${activeSection === id ? 'font-bold text-gray-500 dark:text-white underline' : ''}`}>
{tocItem.text}
</span>
</a>
Expand Down
14 changes: 7 additions & 7 deletions themes/magzine/components/Progress.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'
import { isBrowser } from '@/lib/utils'
import { useEffect, useState } from 'react'

/**
* 顶部页面阅读进度条
Expand All @@ -10,7 +10,8 @@ const Progress = ({ targetRef, showPercent = true }) => {
const currentRef = targetRef?.current || targetRef
const [percent, changePercent] = useState(0)
const scrollListener = () => {
const target = currentRef || (isBrowser && document.getElementById('article-wrapper'))
const target =
currentRef || (isBrowser && document.getElementById('article-wrapper'))
if (target) {
const clientHeight = target.clientHeight
const scrollY = window.pageYOffset
Expand All @@ -28,13 +29,12 @@ const Progress = ({ targetRef, showPercent = true }) => {
}, [])

return (
<div className="h-4 w-full shadow-2xl bg-hexo-light-gray dark:bg-black">
<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}%` }}
>
className='h-4 bg-gray-600 dark:bg-hexo-black-gray duration-200'
style={{ width: `${percent}%` }}>
{showPercent && (
<div className="text-right text-white text-xs">{percent}%</div>
<div className='text-right text-white text-xs'>{percent}%</div>
)}
</div>
</div>
Expand Down
6 changes: 5 additions & 1 deletion themes/magzine/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,11 @@ const LayoutSlug = props => {
{/* 文章区块分为三列 */}
<div className='grid grid-cols-1 lg:grid-cols-5 gap-8 py-12'>
<div className='h-full lg:col-span-1 hidden lg:block'>
<Catalog toc={post?.toc} className='sticky top-20' />
<Catalog
post={post}
toc={post?.toc || []}
className='sticky top-20'
/>
</div>

{/* Notion文章主体 */}
Expand Down

0 comments on commit 1d060a9

Please sign in to comment.