-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocumentIndexer.js
66 lines (52 loc) · 1.66 KB
/
documentIndexer.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
57
58
59
60
61
62
63
64
65
66
const matter = require('gray-matter');
const GithubSlugger = require('github-slugger');
const removeMarkdown = require('remove-markdown');
const stripMarkdown = (content) => {
const strippedContent = content
// Replace newlines with spaces
.replace(/(\r\n|\n|\r)/gm, ' ')
// Remove code blocks
.replace(/```(.*)```/gm, '');
return removeMarkdown(strippedContent);
};
const getBreadcrumbs = (headings, index, level = Infinity, value = []) => {
const target = headings[index];
const newValue = target.level < level ? [target.name, ...value] : value;
return target.level === 1 || index === 0
? newValue
: getBreadcrumbs(headings, index - 1, target.level, newValue);
};
const parseContents = (rawContent) => {
const slugger = new GithubSlugger();
const { content, data } = matter(rawContent);
const headings = content.match(/#{1,}( [ -\w\(\)\.]*)/g).map((heading) => {
const split = heading.split('#');
return {
raw: heading,
level: split.length - 1,
name: split[split.length - 1].trim(),
};
});
const breadcrumbs = headings.map((heading, index) => ({
...heading,
breadcrumbs: getBreadcrumbs(headings, index),
}));
const sections = breadcrumbs.map((heading, index) => {
const nextHeadingIndex =
index < headings.length - 1
? content.lastIndexOf(headings[index + 1].raw)
: content.length;
const currHeadingIndex =
content.lastIndexOf(heading.raw) + heading.raw.length;
return {
...heading,
page: data.title,
hash: slugger.slug(heading.name),
};
});
return {
sections,
parent: data.parent,
};
};
module.exports = parseContents;