import React, { useMemo, useState } from 'react' import Dropdown from 'react-bootstrap/Dropdown' import FormControl from 'react-bootstrap/FormControl' import TocIcon from '@/svgs/list-unordered.svg' import { fromMarkdown } from 'mdast-util-from-markdown' import { visit } from 'unist-util-visit' import { toString } from 'mdast-util-to-string' import GithubSlugger from 'github-slugger' import { useRouter } from 'next/router' export default function Toc ({ text }) { const router = useRouter() if (!text || text.length === 0) { return null } const toc = useMemo(() => { const tree = fromMarkdown(text) const toc = [] const slugger = new GithubSlugger() visit(tree, 'heading', (node, position, parent) => { 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) { return null } return ( {toc.map(v => { return ( router.events.emit('hashChangeStart', `#${v.slug}`, { shallow: true })} >{v.heading} ) })} ) } const CustomToggle = React.forwardRef(({ children, onClick }, ref) => ( { e.preventDefault() onClick(e) }} > {children} )) // forwardRef again here! // Dropdown needs access to the DOM of the Menu to measure it const CustomMenu = React.forwardRef( ({ children, style, className, 'aria-labelledby': labeledBy }, ref) => { const [value, setValue] = useState('') return (
setValue(e.target.value)} value={value} />
) } )