stacker.news/components/table-of-contents.js

100 lines
2.7 KiB
JavaScript
Raw Normal View History

2023-07-13 20:56:57 +00:00
import React, { useMemo, useState } from 'react'
2023-07-24 18:35:05 +00:00
import Dropdown from 'react-bootstrap/Dropdown'
import FormControl from 'react-bootstrap/FormControl'
import TocIcon from '@/svgs/list-unordered.svg'
2022-07-18 21:24:28 +00:00
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'
2023-12-21 00:16:34 +00:00
import { useRouter } from 'next/router'
2022-07-18 21:24:28 +00:00
export default function Toc ({ text }) {
2023-12-21 00:16:34 +00:00
const router = useRouter()
2022-07-18 21:24:28 +00:00
if (!text || text.length === 0) {
return null
}
2023-07-13 20:56:57 +00:00
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])
2022-07-18 21:24:28 +00:00
if (toc.length === 0) {
return null
}
return (
2023-07-24 18:35:05 +00:00
<Dropdown align='end' className='d-flex align-items-center'>
2022-07-18 21:24:28 +00:00
<Dropdown.Toggle as={CustomToggle} id='dropdown-custom-components'>
2023-05-01 20:58:30 +00:00
<TocIcon width={20} height={20} className='mx-2 fill-grey theme' />
2022-07-18 21:24:28 +00:00
</Dropdown.Toggle>
<Dropdown.Menu as={CustomMenu}>
{toc.map(v => {
return (
<Dropdown.Item
2023-07-24 18:35:05 +00:00
className={v.depth === 1 ? 'fw-bold' : ''}
2022-07-18 21:24:28 +00:00
style={{
marginLeft: `${(v.depth - 1) * 5}px`
}}
href={`#${v.slug}`} key={v.slug}
2023-12-21 00:16:34 +00:00
// nextjs router doesn't emit hashChangeStart events
onClick={() => router.events.emit('hashChangeStart', `#${v.slug}`, { shallow: true })}
2022-07-18 21:24:28 +00:00
>{v.heading}
</Dropdown.Item>
)
})}
</Dropdown.Menu>
</Dropdown>
)
}
const CustomToggle = React.forwardRef(({ children, onClick }, ref) => (
<a
href=''
ref={ref}
onClick={(e) => {
e.preventDefault()
onClick(e)
}}
>
{children}
</a>
))
// 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 (
<div
ref={ref}
style={style}
className={className}
aria-labelledby={labeledBy}
>
<FormControl
className='mx-3 my-2 w-auto'
placeholder='filter'
onChange={(e) => setValue(e.target.value)}
value={value}
/>
<ul className='list-unstyled'>
{React.Children.toArray(children).filter(
(child) =>
!value || child.props.children.toLowerCase().includes(value)
)}
</ul>
</div>
)
}
)