-
Notifications
You must be signed in to change notification settings - Fork 67k
Expand file tree
/
Copy pathget-toc-items.ts
More file actions
57 lines (44 loc) · 1.64 KB
/
get-toc-items.ts
File metadata and controls
57 lines (44 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { productMap } from '@/products/lib/all-products'
interface TocItem {
type: 'category' | 'subcategory' | 'article'
href: string
}
interface Page {
relativePath: string
markdown: string
}
const productTOCs = Object.values(productMap)
.filter((product) => !product.external)
.map((product) => product.toc.replace('content/', ''))
const linkString = /{% [^}]*?link.*? \/(.*?) ?%}/m
const linksArray = new RegExp(linkString.source, 'gm')
// return an array of objects like { type: 'category|subcategory|article', href: 'path' }
export default function getTocItems(page: Page): TocItem[] | undefined {
// only process product and category tocs
if (!page.relativePath.endsWith('index.md')) return
if (page.relativePath === 'index.md') return
// ignore content above Table of Contents heading
const pageContent = page.markdown.replace(/[\s\S]*?# Table of contents\n/im, '')
// find array of TOC link strings
const rawItems = pageContent.match(linksArray)
// return an empty array if this is a localized page
if (!rawItems) {
return []
}
return rawItems
.map((item: string) => {
const match = item.match(linkString)
if (!match) return null
const tocItem: TocItem = {} as TocItem
// a product's toc items are always categories
// whereas a category's toc items can be either subcategories or articles
tocItem.type = productTOCs.includes(page.relativePath)
? 'category'
: page.relativePath.includes('/index.md')
? 'subcategory'
: 'article'
tocItem.href = match[1]
return tocItem
})
.filter((item): item is TocItem => item !== null)
}