headings
headings 是 Astro 的 post 提供的一个非常方便的 prop
const { Content, headings } = await post.render();
结构处理
如果我的Markdown文件是如下结构
# headings
## 结构处理
## 构建树形的headings
# 渲染组件
# 让TOC变得丝滑!
## 平滑定位
## 目录同步
得到的headings是一个扁平化的数组
//headings
[
{ "depth": 1, "slug": "处理headings", "text": "处理headings" },
{ "depth": 2, "slug": "headings结构", "text": "headings结构" },
{ "depth": 2, "slug": "构建树形的headings", "text": "构建树形的headings" },
{ "depth": 1, "slug": "渲染组件", "text": "渲染组件" },
{ "depth": 1, "slug": "让toc变得丝滑", "text": "让TOC变得丝滑!" },
{ "depth": 2, "slug": "平滑定位", "text": "平滑定位" },
{ "depth": 2, "slug": "目录同步", "text": "目录同步" }
]
然而一般toc的结构都是<ol>
> <li>
> <ol>
,将headings聚合成树形会比较好实现
构建树形的headings
通常情况下三级目录就已经足够了,所以我这里并没有用递归,只是简单处理了下
import type { MarkdownHeading } from 'astro';
type HeadingWithSubheadings = MarkdownHeading & {
subheadings?: HeadingWithSubheadings[];
};
const grouppedHeadings = headings.reduce((array, heading) => {
if (heading.depth === 1) {
array.push({ ...heading, subheadings: [] });
} else if (heading.depth === 2) {
array.at(-1)?.subheadings?.push({ ...heading, subheadings: [] });
} else if (heading.depth === 3) {
array.at(-1)?.subheadings?.at(-1)?.subheadings?.push({ ...heading })
}
return array;
}, [] as HeadingWithSubheadings[]);
然后就得到了
//grouppedHeadings
[
{
"depth": 1, "slug": "headings", "text": "headings",
"subheadings": [
{ "depth": 2, "slug": "结构处理", "text": "结构处理", "subheadings": [] },
{ "depth": 2, "slug": "构建树形的headings", "text": "构建树形的headings", "subheadings": [] }
]
},
{
"depth": 1, "slug": "渲染组件", "text": "渲染组件",
"subheadings": []
},
{
"depth": 1, "slug": "让toc变得丝滑", "text": "让TOC变得丝滑!",
"subheadings": [
{ "depth": 2, "slug": "平滑定位", "text": "平滑定位", "subheadings": [] },
{ "depth": 2, "slug": "目录同步", "text": "目录同步", "subheadings": [] }
]
}
]
渲染组件
这里采用了递归缩减行数 :p 如果用astro写三层ol缩进将会看着极其恶心
<ol>
{(()=>{
const h = (heading:HeadingWithSubheadings,number:string) => (
<li>
<a href={`#${heading.slug}`}>{number}. {heading.text}</a>
{ heading.subheadings && <ol> { heading.subheadings.map((subheading, i) => h(subheading,`${number}.${i+1}`)) } </ol> }
</li>
)
return grouppedHeadings.map((heading, i)=> h(heading,`${i+1}`))
})()}
</ol>
这样,我们就得到了一坨三级toc目录~
<ol>
<li>
<a>一级</a>
<ol>
<li>
<a>二级</a>
<ol>
<li>
<a>三级</a>
</li>
</ol>
</li>
</ol>
</li>
...
<li>
...
</li>
</ol>
让TOC变得丝滑!
上面实现的目录定位十分生硬,没有那种响应式的丝滑感觉 :( 还得让它变得高级起来!
实现下面的效果时,先准备好一个对应关系的列表
const toc = [...document.querySelectorAll(".card-toc a")].map((a) => ({
link: a as HTMLElement,
target: document.querySelector(a.getAttribute("href")!)! as HTMLElement,
}))
这个列表的每个对象的 link
= <a>
, target
= <h1><h2>...
,
平滑定位
很简单,阻止 <a>
标签冒泡,通过window.scrollTo(smooth)
定位到<h1>
目标就好了
toc.forEach(({link,target}) => {
link.addEventListener('click', event => {
event.preventDefault()
window.scrollTo({ top: target.offsetTop, behavior: 'smooth' });
})
})
目录同步
最开始我是使用window.addEventListener("scroll")
去实现的,但是通过监听滚动事件,开销会比较大,而且同步并不是很丝滑,最终找到了IntersectionObserver
的方案,开销比监听滚动事件小很多,稍微修改了一下,效果十分的amazing!无敌!
const targetsObserver = new IntersectionObserver(targets => {
targets.forEach(entry => {
const link = document.querySelector(`.card-toc a[href="#${entry.target.getAttribute('id')}"]`)!
link.classList[entry.intersectionRatio > 0 ? "add" : "remove"]('active')
});
});
toc.forEach(({target})=>targetsObserver.observe(target))
/* 弃用的代码
toc.forEach(({link, target})=>{
window.addEventListener("scroll", throttle(()=> {
const {offsetTop:top , clientHeight:height} = tocTarget
if (window.scrollY >= top && window.scrollY < top+height) {
toc.forEach(({link:otherLink})=> otherLink.classList.remove('active'))
link.classList.add('active')
}
},300))
})
*/
稍微加个样式
.card-toc a.active {
color: #49b1f5;
text-decoration: none;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-o-transition: all 0.2s;
-ms-transition: all 0.2s;
transition: all 0.2s;
}
最终效果就是这个博客的toc了,纵享丝滑~