-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
65 lines (62 loc) · 2.26 KB
/
index.ts
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
import unifiedTypes, { unified } from "unified";
import { modifyChildren as unistUtilModifyChildren } from "unist-util-modify-children";
import { toText as hastUtilToText } from "hast-util-to-text";
import * as Shiki from "shiki";
import rehypeParse from "rehype-parse";
import { html } from "@leafac/html";
const attacher: unifiedTypes.Plugin<
[
{
highlighter: Shiki.Highlighter | { [key: string]: Shiki.Highlighter };
throwOnUnsupportedLanguage?: boolean;
}
]
> =
({ highlighter, throwOnUnsupportedLanguage = false }) =>
(tree) => {
unistUtilModifyChildren((node: any, index, parent) => {
if (
node.tagName === "pre" &&
Array.isArray(node.children) &&
node.children.length === 1 &&
node.children[0].tagName === "code" &&
typeof node.children[0].properties === "object" &&
Array.isArray(node.children[0].properties.className) &&
typeof node.children[0].properties.className[0] === "string" &&
node.children[0].properties.className[0].startsWith("language-")
) {
const code = hastUtilToText(node).slice(0, -1);
const language = node.children[0].properties.className[0].slice(
"language-".length
);
let output: string;
try {
if (typeof highlighter.codeToHtml === "function")
output = highlighter.codeToHtml(code, language);
else
output = html`
<div class="rehype-shiki">
$${Object.entries(highlighter).map(
([name, highlighter]: [string, Shiki.Highlighter]) =>
html`
<div class="${name}">
$${highlighter.codeToHtml(code, language)}
</div>
`
)}
</div>
`;
} catch (error) {
if (throwOnUnsupportedLanguage) throw error;
else return;
}
const parsedOutput = hastParser.parse(output);
parsedOutput.children.find(
(child) => child.type === "element"
)!.position = node.position;
parent.children[index] = parsedOutput;
}
})(tree as any);
};
const hastParser = unified().use(rehypeParse, { fragment: true });
export default attacher;