Skip to content

Commit

Permalink
feat(plugin): add rehype-starry-night-inline plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
naiyerasif committed Apr 25, 2024
1 parent ce797a3 commit 45f3c9f
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/rehype-starry-night-inline/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
});
};
}

0 comments on commit 45f3c9f

Please sign in to comment.