|
| 1 | +import { visit } from 'unist-util-visit' |
| 2 | +import type { Properties } from 'hast' |
| 3 | +import type { Root } from 'mdast' |
| 4 | +import type { Plugin } from '@/types' |
| 5 | +import type { TocOptions, TocItems } from './types' |
| 6 | + |
| 7 | +/** |
| 8 | + * A custom `Remark` plugin that creates `Table of Content` (Toc). |
| 9 | + * |
| 10 | + * Automatically adds a link with the appropriate attributes to the headings. |
| 11 | + * |
| 12 | + * It also stores Toc items to `frontmatter` for easy access. |
| 13 | + * |
| 14 | + * @example |
| 15 | + * |
| 16 | + * ```ts |
| 17 | + * import { svelteMarkdown } from '@sveltek/markdown' |
| 18 | + * import { remarkToc } from '@sveltek/unplugins' |
| 19 | + * |
| 20 | + * svelteMarkdown({ |
| 21 | + * plugins: { |
| 22 | + * remark: [remarkToc] |
| 23 | + * } |
| 24 | + * }) |
| 25 | + * ``` |
| 26 | + * |
| 27 | + * Or with options: |
| 28 | + * |
| 29 | + * ```js |
| 30 | + * svelteMarkdown({ |
| 31 | + * plugins: { |
| 32 | + * remark: [[remarkToc, { depth: 3 }]] |
| 33 | + * } |
| 34 | + * }) |
| 35 | + * ``` |
| 36 | + */ |
| 37 | +export const remarkToc: Plugin<[TocOptions?], Root> = ( |
| 38 | + options: TocOptions = {}, |
| 39 | +) => { |
| 40 | + const { depth = 3, links = true } = options |
| 41 | + |
| 42 | + return (tree, vfile) => { |
| 43 | + const frontmatter = vfile.data.frontmatter as { |
| 44 | + toc: TocItems |
| 45 | + } |
| 46 | + |
| 47 | + const toc: TocItems = [] |
| 48 | + let i = 0 |
| 49 | + |
| 50 | + visit(tree, 'heading', (node) => { |
| 51 | + const [child] = node.children |
| 52 | + |
| 53 | + let value = '' |
| 54 | + let id = '' |
| 55 | + |
| 56 | + if (child.type === 'text') { |
| 57 | + value = child.value |
| 58 | + id = value |
| 59 | + .toLowerCase() |
| 60 | + .replace(/[^a-z0-9\s-]/g, '') |
| 61 | + .trim() |
| 62 | + .replace(/\s+/g, '-') |
| 63 | + } |
| 64 | + |
| 65 | + if (links) { |
| 66 | + node.children = [] |
| 67 | + node.children.push({ |
| 68 | + type: 'link', |
| 69 | + url: `#${id}`, |
| 70 | + children: [{ type: 'text', value }], |
| 71 | + }) |
| 72 | + } |
| 73 | + |
| 74 | + const data = (node.data || (node.data = {})) as { |
| 75 | + hProperties?: Properties |
| 76 | + } |
| 77 | + const props = data.hProperties || (data.hProperties = {}) |
| 78 | + |
| 79 | + if (node.depth > 1 && node.depth <= depth) { |
| 80 | + if (toc.some((h) => h.id === id)) id = `${id}-${i + 1}` |
| 81 | + if (!props.id) props.id = id |
| 82 | + toc.push({ id, depth: node.depth, value }) |
| 83 | + } |
| 84 | + }) |
| 85 | + |
| 86 | + frontmatter.toc = toc |
| 87 | + } |
| 88 | +} |
0 commit comments