memoize table of contents

This commit is contained in:
keyan 2023-07-13 15:56:57 -05:00
parent 3c711b6083
commit 7a4ba715e0
1 changed files with 11 additions and 8 deletions

View File

@ -1,4 +1,4 @@
import React, { useState } from 'react' import React, { useMemo, useState } from 'react'
import { Dropdown, FormControl } from 'react-bootstrap' import { Dropdown, FormControl } from 'react-bootstrap'
import TocIcon from '../svgs/list-unordered.svg' import TocIcon from '../svgs/list-unordered.svg'
import { fromMarkdown } from 'mdast-util-from-markdown' import { fromMarkdown } from 'mdast-util-from-markdown'
@ -11,13 +11,16 @@ export default function Toc ({ text }) {
return null return null
} }
const tree = fromMarkdown(text) const toc = useMemo(() => {
const toc = [] const tree = fromMarkdown(text)
const slugger = new GithubSlugger() const toc = []
visit(tree, 'heading', (node, position, parent) => { const slugger = new GithubSlugger()
const str = toString(node) visit(tree, 'heading', (node, position, parent) => {
toc.push({ heading: str, slug: slugger.slug(str.replace(/[^\w\-\s]+/gi, '')), depth: node.depth }) const str = toString(node)
}) toc.push({ heading: str, slug: slugger.slug(str.replace(/[^\w\-\s]+/gi, '')), depth: node.depth })
})
return toc
}, [text])
if (toc.length === 0) { if (toc.length === 0) {
return null return null