-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathindex.js
56 lines (44 loc) · 1.38 KB
/
index.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const { Lexer } = require('marked')
const { slugify } = require('../nunjucks/filters')
/**
* Metalsmith extract headings plugin
*
* @param {string[]} config.pattern - File match glob patterns
* @returns {import('metalsmith').Plugin} Metalsmith plugin
*/
const extractPageHeadings = () => (files, metalsmith, done) => {
Object.keys(files).forEach((file) => {
if (!file.endsWith('.njk') && !file.endsWith('.md')) {
return
}
const { contents, headings = [] } = files[file]
const extracted = []
// Heading overrides from frontmatter (e.g. aliases)
const overrides = Object.fromEntries(
headings.map((heading) => [slugify(heading.text), heading])
)
const lexer = new Lexer()
const tokens = lexer.lex(contents.toString())
tokens.forEach((token) => {
if (token.type !== 'heading') {
return
}
const url = slugify(token.text)
const heading = overrides[url]
// Add extracted heading
extracted.push({
depth: token.depth,
text: token.text,
url: heading?.url ?? url,
aliases: heading?.aliases,
// Flags to opt out of default behaviour
ignoreInPageNav: !!heading?.ignoreInPageNav,
ignoreInSearch: !!heading?.ignoreInSearch
})
})
// Add extracted headings
files[file].headings = extracted
})
done()
}
module.exports = extractPageHeadings