-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
40 lines (33 loc) · 1.19 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
import defu from "defu";
import { createStarryNight, all } from "@wooorm/starry-night";
import { visit } from "unist-util-visit";
import { toString } from "hast-util-to-string";
const defaults = {
classNamePrefix: "hl"
};
export default function rehypeStarryNightInline(userOptions = {}) {
const { aliases = {}, grammars = all, classNamePrefix } = defu(userOptions, defaults);
const starryNightPromise = createStarryNight(grammars);
return async function (tree) {
const starryNight = await starryNightPromise;
visit(tree, "element", (node, index, parent) => {
const annotatedInlineCode = node.tagName === "code" && ("lang" in node.properties);
if (!parent || index === null || node.tagName !== "code" || !annotatedInlineCode) {
return;
}
const { lang, ...props } = node.properties;
const languageId = aliases[lang] || lang;
const scope = starryNight.flagToScope(languageId);
if (scope) {
const fragment = starryNight.highlight(toString(node), scope);
node.children = fragment.children;
node.properties = {
className: [`${classNamePrefix}-inline`, `${classNamePrefix}-${languageId}`],
...props
};
} else {
node.properties = props;
}
});
};
}