forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-toc-items.js
41 lines (32 loc) · 1.26 KB
/
get-toc-items.js
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
import { productMap } from './all-products.js'
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|maptopic|article', href: 'path' }
export default function getTocItems(page) {
// 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) => {
const tocItem = {}
// a product's toc items are always categories
// whereas a category's toc items can be either maptopics or articles
tocItem.type = productTOCs.includes(page.relativePath)
? 'category'
: item.includes('topic_')
? 'maptopic'
: 'article'
tocItem.href = item.match(linkString)[1]
return tocItem
})
}