-
-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathmarkdown.js
More file actions
72 lines (64 loc) · 1.93 KB
/
Copy pathmarkdown.js
File metadata and controls
72 lines (64 loc) · 1.93 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkGfm from "remark-gfm";
import remarkFrontmatter from "remark-frontmatter";
import remarkRehype from "remark-rehype";
import rehypeSlug from "rehype-slug";
import rehypeStringify from "rehype-stringify";
import { matter } from "vfile-matter";
const remarkVfileMatter = options => (tree, file) => {
matter(file);
};
const remarkCodeblocks = options => (tree, file) => {
const { children } = tree;
const codeblocks = {};
const formatter = value => {
// Strip newlines and weird spacing
return value
.replace(/\n/g, " ")
.replace(/\s+/g, " ")
.replace(/\(\s+/g, "(")
.replace(/\s+\)/g, ")");
};
children.forEach(child => {
if (child.type === "code" && child.value) {
const { meta, lang } = child;
if (meta === "sig" && lang === "re") {
if (codeblocks[lang] == null) {
codeblocks[lang] = [];
}
codeblocks[lang].push(formatter(child.value));
}
}
});
Object.assign(file.data, { codeblocks });
};
const rehypeHeaders = options => (tree, file) => {
const headers = [];
let mainHeader;
tree.children.forEach(child => {
if (child.tagName === "h1") {
if (child.children.length > 0) {
mainHeader = child.children.map(element => element.value).join("");
}
}
if (child.tagName === "h2") {
if (child.children.length > 0) {
const id = child.properties.id || "";
const name = child.children.map(element => element.value).join("");
headers.push({ name, href: id });
}
}
});
Object.assign(file.data, { headers, mainHeader });
};
export const defaultProcessor = unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkFrontmatter, [{ type: 'yaml', marker: '-' }])
.use(remarkVfileMatter)
.use(remarkCodeblocks)
.use(remarkRehype)
.use(rehypeSlug)
.use(rehypeHeaders)
.use(rehypeStringify);