|
| 1 | +import { visit } from "unist-util-visit"; |
| 2 | +import { toString } from "hast-util-to-string"; |
| 3 | +import type { RefractorElement } from "refractor"; |
| 4 | +import mermaid from "mermaid"; |
| 5 | +import { fromHtmlIsomorphic } from "hast-util-from-html-isomorphic"; |
| 6 | +import { getCodeLanguage } from "./utils.js"; |
| 7 | + |
| 8 | +let count = 0; |
| 9 | + |
| 10 | +mermaid.initialize({ |
| 11 | + startOnLoad: false, |
| 12 | + themeVariables: { |
| 13 | + fontSize: "14px", |
| 14 | + }, |
| 15 | +}); |
| 16 | + |
| 17 | +// Reference https://github.com/remcohaszing/rehype-mermaid |
| 18 | +export function rehypeMermaid() { |
| 19 | + return async (tree: RefractorElement) => { |
| 20 | + const promises: Promise<void>[] = []; |
| 21 | + |
| 22 | + function visitor( |
| 23 | + node: RefractorElement, |
| 24 | + index: number | undefined, |
| 25 | + parent: RefractorElement | undefined |
| 26 | + ) { |
| 27 | + if (!parent || parent.tagName !== "pre" || node.tagName !== "code") { |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + const lang = getCodeLanguage(node); |
| 32 | + |
| 33 | + if (lang !== "mermaid") { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + promises.push( |
| 38 | + (async () => { |
| 39 | + const id = `mermaid-${count++}`; |
| 40 | + |
| 41 | + const { svg } = await mermaid.render(id, toString(node)); |
| 42 | + const replacements = fromHtmlIsomorphic(svg, { fragment: true }) |
| 43 | + .children as RefractorElement[]; |
| 44 | + parent.children.splice(index!, 1, ...replacements); |
| 45 | + parent.properties.className = ( |
| 46 | + (parent.properties.className as string[]) || [] |
| 47 | + ).concat("mermaid"); |
| 48 | + })() |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + visit(tree, "element", visitor); |
| 53 | + |
| 54 | + await Promise.all(promises); |
| 55 | + }; |
| 56 | +} |
0 commit comments