滚动目录

This commit is contained in:
tangly1024
2022-03-29 13:15:16 +08:00
parent 60c12ba775
commit 73bee68ac0
6 changed files with 118 additions and 99 deletions

View File

@@ -1,4 +1,4 @@
import React from 'react'
import React, { useRef } from 'react'
import throttle from 'lodash.throttle'
import { uuidToId } from 'notion-utils'
import Progress from './Progress'
@@ -23,6 +23,10 @@ const Catalog = ({ toc }) => {
}
}, [])
// 目录自动滚动
const tRef = useRef(null)
const tocIds = []
// 同步选中目录事件
const [activeSection, setActiveSection] = React.useState(null)
const throttleMs = 100
@@ -49,35 +53,36 @@ const Catalog = ({ toc }) => {
break
}
setActiveSection(currentSectionId)
const index = tocIds.indexOf(currentSectionId) || 0
tRef?.current?.scrollTo({ top: 28 * index, behavior: 'smooth' })
}, throttleMs))
return <div className='px-3'>
<div className='w-full py-1'>
<Progress/>
</div>
<nav className='font-sans overflow-y-auto scroll-hidden text-black'>
{toc.map((tocItem) => {
const id = uuidToId(tocItem.id)
return (
<a
key={id}
href={`#${id}`}
className={`notion-table-of-contents-item duration-300 transform font-light dark:text-gray-300
notion-table-of-contents-item-indent-level-${tocItem.indentLevel} `}
>
<span
style={{
display: 'inline-block',
marginLeft: tocItem.indentLevel * 16
}}
className={`${activeSection === id && ' font-bold text-green-500 underline'}`}
>
{tocItem.text}
</span>
</a>
)
})}
</nav>
<div className='overflow-y-auto max-h-96' ref={tRef}>
<nav className='h-full font-sans 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 font-light dark:text-gray-300
notion-table-of-contents-item-indent-level-${tocItem.indentLevel} `}
>
<span style={{ display: 'inline-block', marginLeft: tocItem.indentLevel * 16 }}
className={`${activeSection === id && ' font-bold text-green-500 underline'}`}
>
{tocItem.text}
</span>
</a>
)
})}
</nav>
</div>
<JumpToTopButton className='text-gray-400 hover:text-green-500 hover:bg-gray-100 py-1 duration-200'/>
</div>
}