get-toc.tsx50 lines · main
1import { remark } from 'remark'
2import type { PluggableList } from 'unified'
3import type { Compatible } from 'vfile'
4
5import { remarkHeading } from '../mdx-plugins/remark-heading'
6import type { TableOfContents } from '../types'
7
8/**
9 * Get Table of Contents from markdown/mdx document (using remark)
10 *
11 * @param content - Markdown content or file
12 */
13export function getTableOfContents(content: Compatible): TableOfContents
14
15/**
16 * Get Table of Contents from markdown/mdx document (using remark)
17 *
18 * @param content - Markdown content or file
19 * @param remarkPlugins - remark plugins to be applied first
20 */
21export function getTableOfContents(
22 content: Compatible,
23 remarkPlugins: PluggableList
24): Promise<TableOfContents>
25
26export function getTableOfContents(
27 content: Compatible,
28 remarkPlugins?: PluggableList
29): TableOfContents | Promise<TableOfContents> {
30 if (remarkPlugins) {
31 return remark()
32 .use(remarkPlugins as any)
33 .use(remarkHeading)
34 .process(content)
35 .then((result) => {
36 if ('toc' in result.data) return result.data.toc as TableOfContents
37
38 return []
39 })
40 }
41
42 // compatible with previous versions
43 const result = remark().use(remarkHeading).processSync(content)
44
45 if ('toc' in result.data) return result.data.toc as TableOfContents
46
47 return []
48}
49
50export type { TableOfContents, TOCItemType } from '../types'