|
| 1 | +import React from 'react'; |
| 2 | +import Link from '@docusaurus/Link'; |
| 3 | +import {useDoc} from '@docusaurus/plugin-content-docs/client'; |
| 4 | +import {PAGE_TOP_ID} from '@theme/DocItem/Content'; |
| 5 | + |
| 6 | +/* Ejected from @docusaurus/theme-classic to put the page title at the top of |
| 7 | + the table of contents. Docusaurus builds the list from h2/h3 headings alone, |
| 8 | + so the title -- rendered as a synthetic h1 from front matter -- never appears. |
| 9 | +
|
| 10 | + Ejected rather than wrapped because the component recurses into itself, so a |
| 11 | + wrapper cannot reach inside the list it renders. Both the desktop sidebar and |
| 12 | + the mobile "on this page" dropdown render through here, so they stay in step. */ |
| 13 | + |
| 14 | +/* Docusaurus only renders a synthetic title when the page has not hidden it and |
| 15 | + the content does not already open with its own h1. src/theme/DocItem/Content |
| 16 | + makes the same test before adding the anchor; keep the two in step. */ |
| 17 | +function useSyntheticTitle() { |
| 18 | + const {metadata, frontMatter, contentTitle} = useDoc(); |
| 19 | + if (frontMatter.hide_title || typeof contentTitle !== 'undefined') { |
| 20 | + return null; |
| 21 | + } |
| 22 | + return metadata.title; |
| 23 | +} |
| 24 | + |
| 25 | +/* A plain <a>, not a Docusaurus <Link>, on purpose. The build-time broken-anchor |
| 26 | + checker inspects <Link> only, and derives the valid anchors from the page's |
| 27 | + headings -- it cannot see an id added by a theme component, so a <Link> here |
| 28 | + reports a broken anchor on every page that has a title. */ |
| 29 | +function PageTitleItem({linkClassName}) { |
| 30 | + const title = useSyntheticTitle(); |
| 31 | + if (!title) { |
| 32 | + return null; |
| 33 | + } |
| 34 | + return ( |
| 35 | + <li> |
| 36 | + <a className={linkClassName ?? undefined} href={`#${PAGE_TOP_ID}`}> |
| 37 | + {title} |
| 38 | + </a> |
| 39 | + </li> |
| 40 | + ); |
| 41 | +} |
| 42 | + |
| 43 | +function TOCItemTree({toc, className, linkClassName, isChild}) { |
| 44 | + if (!toc.length) { |
| 45 | + return null; |
| 46 | + } |
| 47 | + return ( |
| 48 | + <ul className={isChild ? undefined : className}> |
| 49 | + {!isChild && <PageTitleItem linkClassName={linkClassName} />} |
| 50 | + {toc.map((heading) => ( |
| 51 | + <li key={heading.id}> |
| 52 | + <Link |
| 53 | + to={`#${heading.id}`} |
| 54 | + className={linkClassName ?? undefined} |
| 55 | + // Developer provided the HTML, so assume it's safe. |
| 56 | + dangerouslySetInnerHTML={{__html: heading.value}} |
| 57 | + /> |
| 58 | + <TOCItemTree |
| 59 | + isChild |
| 60 | + toc={heading.children} |
| 61 | + className={className} |
| 62 | + linkClassName={linkClassName} |
| 63 | + /> |
| 64 | + </li> |
| 65 | + ))} |
| 66 | + </ul> |
| 67 | + ); |
| 68 | +} |
| 69 | + |
| 70 | +// Memo only the tree root is enough |
| 71 | +export default React.memo(TOCItemTree); |
0 commit comments