🤖
686 in / 669 out / 1355 total tokens
TOC(목차)를 클릭하면 해당 섹션으로 스크롤 이동하도록 만들었다. heading 태그에 id가 없어서 앵커 이동이 안 되는 게 문제였다.
rehypeHeadingIds 커스텀 플러그인을 새로 만들었다. extractHeadings에서 headings를 추출할 때 쓰는 로직과 동일하게 슬러그를 생성해서 id 속성을 부여한다. 이렇게 하면 TOC의 링크(href: #slug)와 실제 heading의 id가 매칭된다.
const rehypeHeadingIds: Plugin<[], Root> = () => {
return (tree) => {
visit(tree, "element", (node: Element) => {
if (headingTags.includes(node.tagName as HeadingTag)) {
const text = getTextContent(node);
const slug = slugify(text);
node.properties = { ...node.properties, id: slug };
}
});
};
};플러그인 순서가 중요하다. rehypePrettyCode보다 앞서야 한다. 그래야 코드 블록 변환 전에 heading id가 먼저 붙는다.