-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (56 loc) · 1.84 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
57
58
59
import { visit, SKIP } from "unist-util-visit";
import { rehype } from "rehype";
import { createRequire } from "node:module";
import { h } from "hastscript";
import { getBinaryPath } from './prebuilt.js';
import stringByteSlice from "string-byte-slice";
const require = createRequire(import.meta.url);
const core = require(getBinaryPath());
const exampleScopeMap = {
javascript: "source.js",
sh: "source.bash",
xml: "source.xml",
};
const isCodeBlockElement = (node) => node.tagName === "code";
export default function rehypeTreeSitter(options) {
if (options === undefined)
throw new Error("Need to provide `options.treeSitterGrammarRoot`");
if (options.treeSitterGrammarRoot === undefined)
throw new Error("Need to provide `options.treeSitterGrammarRoot`");
return function (tree) {
visit(tree, isCodeBlockElement, (node, index, parent) => {
if (Object.keys(node.properties).length === 0) return;
const code = node.children[0].value;
const inputLanguage = node.properties.className[0];
node.children = [];
const highlightStack = [];
const language = inputLanguage.split("-")[1];
core.driver(
options.treeSitterGrammarRoot,
(options.scopeMap || exampleScopeMap)[language] ?? "",
language,
code,
(event) => {
if (event.source !== undefined) {
const sourceChunk = stringByteSlice(
code,
Number(event.source.start),
Number(event.source.end)
);
if (highlightStack.length === 0) {
node.children.push({ type: "text", value: sourceChunk });
} else {
node.children.push(
h("span", { class: highlightStack.join(" ") }, sourceChunk)
);
}
} else if (event.highlightStart !== undefined) {
highlightStack.push(event.highlightStart.highlightName);
} else if (event === "HighlightEnd") {
highlightStack.pop();
}
}
);
});
};
}