-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(plugin): add rehype-starry-night-inline plugin
- Loading branch information
1 parent
ce797a3
commit 45f3c9f
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}); | ||
}; | ||
} |