@scalar/code-highlight
Version:
Central methods and themes for code highlighting in Scalar projects
43 lines (42 loc) • 1.65 kB
JavaScript
import rehypeParse from "rehype-parse";
import rehypeStringify from "rehype-stringify";
import { unified } from "unified";
import { visit } from "unist-util-visit";
import { lowlightLanguageMappings } from "../constants.js";
import { rehypeHighlight } from "../rehype-highlight/index.js";
import { codeBlockLinesPlugin } from "./line-numbers.js";
function syntaxHighlight(codeString, options) {
const credentials = (typeof options?.maskCredentials === "string" ? [options.maskCredentials] : options?.maskCredentials ?? []).filter((c) => {
if (c.length < 3) {
return false;
}
return true;
});
const className = `language-${lowlightLanguageMappings[options.lang] ?? options.lang}`;
const nullPlugin = () => {
};
const html = unified().use(rehypeParse, { fragment: true }).use(injectRawCodeStringPlugin(codeString)).use(rehypeHighlight, {
languages: options.languages
}).use(options?.lineNumbers ? codeBlockLinesPlugin : nullPlugin).use(rehypeStringify).processSync(`<pre><code class="${className}"></code></pre>`);
const htmlString = html.toString();
return credentials.length ? credentials.reduce(
(acc, credential) => acc.split(credential).join(`<span class="credential"><span class="credential-value">${credential}</span></span>`),
htmlString
) : htmlString;
}
function injectRawCodeStringPlugin(rawCodeString) {
return () => (tree) => {
visit(tree, "element", (node) => {
if (node.tagName === "code") {
node.children.push({
type: "text",
value: rawCodeString
});
}
});
};
}
export {
syntaxHighlight
};
//# sourceMappingURL=highlight.js.map