|
| 1 | +import { TocEntry } from '@stefanprobst/rehype-extract-toc'; |
| 2 | +import { Pluggable } from './rehypeSubtitle'; |
| 3 | +import { createMdxElement } from './createMdxElement'; |
| 4 | + |
| 5 | +const ROOT = 'QuickNav.Root'; |
| 6 | +const TITLE = 'QuickNav.Title'; |
| 7 | +const LIST = 'QuickNav.List'; |
| 8 | +const ITEM = 'QuickNav.Item'; |
| 9 | +const LINK = 'QuickNav.Link'; |
| 10 | + |
| 11 | +export const rehypeQuickNav: Pluggable = () => { |
| 12 | + return (tree, file) => { |
| 13 | + const toc = file.data.toc; |
| 14 | + if (!toc) { |
| 15 | + return; |
| 16 | + } |
| 17 | + const root = createMdxElement({ |
| 18 | + name: ROOT, |
| 19 | + children: toc.flatMap(getNodeFromEntry).filter(Boolean), |
| 20 | + }); |
| 21 | + |
| 22 | + if (!toc.length) { |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + tree.children.unshift(root); |
| 27 | + }; |
| 28 | +}; |
| 29 | + |
| 30 | +function getNodeFromEntry({ value, depth, id, children }: TocEntry) { |
| 31 | + const sub = createMdxElement({ |
| 32 | + name: LIST, |
| 33 | + children: [], |
| 34 | + }); |
| 35 | + |
| 36 | + // Ignore <h4>'s and below |
| 37 | + if (depth < 3 && children?.length) { |
| 38 | + sub.children = children.map(getNodeFromEntry); |
| 39 | + } |
| 40 | + |
| 41 | + if (depth === 1) { |
| 42 | + // Insert "(Top)" link |
| 43 | + sub.children?.unshift(getNodeFromEntry({ value: '(Top)', id: '', depth: 2 })); |
| 44 | + |
| 45 | + return [ |
| 46 | + // Insert a top-level title |
| 47 | + createMdxElement({ |
| 48 | + name: TITLE, |
| 49 | + children: [{ type: 'text', value }], |
| 50 | + }), |
| 51 | + sub, |
| 52 | + ]; |
| 53 | + } |
| 54 | + |
| 55 | + const link = createMdxElement({ |
| 56 | + name: LINK, |
| 57 | + children: [{ type: 'text', value }], |
| 58 | + props: { |
| 59 | + href: `#${id}`, |
| 60 | + }, |
| 61 | + }); |
| 62 | + |
| 63 | + return createMdxElement({ |
| 64 | + name: ITEM, |
| 65 | + children: [link, sub], |
| 66 | + }); |
| 67 | +} |
0 commit comments