80 lines
2.2 KiB
TypeScript
80 lines
2.2 KiB
TypeScript
|
import { refractor } from "https://esm.sh/refractor@4.8.1";
|
||
|
import { visit } from "https://esm.sh/unist-util-visit@5.0.0";
|
||
|
import { toString } from "https://esm.sh/hast-util-to-string@2.0.0";
|
||
|
|
||
|
import jsx from "https://esm.sh/refractor/lang/jsx";
|
||
|
import javascript from "https://esm.sh/refractor/lang/javascript";
|
||
|
import css from "https://esm.sh/refractor/lang/css";
|
||
|
import cssExtras from "https://esm.sh/refractor/lang/css-extras";
|
||
|
import jsExtras from "https://esm.sh/refractor/lang/js-extras";
|
||
|
import sql from "https://esm.sh/refractor/lang/sql";
|
||
|
import typescript from "https://esm.sh/refractor/lang/typescript";
|
||
|
import swift from "https://esm.sh/refractor/lang/swift";
|
||
|
import objectivec from "https://esm.sh/refractor/lang/objectivec";
|
||
|
import markdown from "https://esm.sh/refractor/lang/markdown";
|
||
|
import json from "https://esm.sh/refractor/lang/json";
|
||
|
|
||
|
refractor.register(jsx);
|
||
|
refractor.register(json);
|
||
|
refractor.register(typescript);
|
||
|
refractor.register(javascript);
|
||
|
refractor.register(css);
|
||
|
refractor.register(cssExtras);
|
||
|
refractor.register(jsExtras);
|
||
|
refractor.register(sql);
|
||
|
refractor.register(swift);
|
||
|
refractor.register(objectivec);
|
||
|
refractor.register(markdown);
|
||
|
|
||
|
refractor.alias({ jsx: ["js"] });
|
||
|
refractor.alias({typescript:["ts"]})
|
||
|
|
||
|
const getLanguage = (node) => {
|
||
|
const className = node.properties.className || [];
|
||
|
|
||
|
for (const classListItem of className) {
|
||
|
if (classListItem.slice(0, 9) === "language-") {
|
||
|
return classListItem.slice(9).toLowerCase();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return null;
|
||
|
};
|
||
|
|
||
|
const rehypePrism = (options) => {
|
||
|
options = options || {};
|
||
|
|
||
|
return (tree) => {
|
||
|
visit(tree, "element", visitor);
|
||
|
};
|
||
|
|
||
|
function visitor(node, index, parent) {
|
||
|
if (!parent || parent.tagName !== "pre" || node.tagName !== "code") {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
const lang = getLanguage(node);
|
||
|
|
||
|
if (lang === null) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
let result;
|
||
|
try {
|
||
|
parent.properties.className = (parent.properties.className || []).concat(
|
||
|
"language-" + lang,
|
||
|
);
|
||
|
result = refractor.highlight(toString(node), lang);
|
||
|
} catch (err) {
|
||
|
if (options.ignoreMissing && /Unknown language/.test(err.message)) {
|
||
|
return;
|
||
|
}
|
||
|
throw err;
|
||
|
}
|
||
|
|
||
|
node.children = result;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
export default rehypePrism;
|