Skip to content

Commit

Permalink
refactor: rehype-mermaid
Browse files Browse the repository at this point in the history
  • Loading branch information
taga3s committed Dec 22, 2024
1 parent 5daead5 commit 6894a69
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 10 deletions.
4 changes: 0 additions & 4 deletions app/packages/rehype-mermaid/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,3 @@
## features

- Generating Mermaid Diagrams

## How to use?

<img src="./docs/assets/rehype-mermaid-sample.png" alt="example usage of rehype-mermaid" />
Binary file not shown.
14 changes: 8 additions & 6 deletions app/packages/rehype-mermaid/rehypeMermaid.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Plugin } from "unified";
import type { Plugin, Transformer } from "unified";
import type { Text, Parent, Root } from "hast";
import { visit } from "unist-util-visit";
import { renderMermaid } from "@mermaid-js/mermaid-cli";
Expand All @@ -23,8 +23,8 @@ const rehypeMermaid: Plugin<[], Root> = () => {

const checkIsMermaid = (lang: string): boolean => lang === "mermaid";

return async (tree) => {
const mermaidCodeBlocks: MermaidCodeBlock[] = [];
const transformer: Transformer<Root> = async (tree) => {
const mermaidCodeBlockPromises: MermaidCodeBlock[] = [];

visit(tree, "element", (node, index, parent) => {
// Check if the node is a pre tag with a single child
Expand Down Expand Up @@ -61,11 +61,11 @@ const rehypeMermaid: Plugin<[], Root> = () => {
const isMermaid = checkIsMermaid(lang);

if (isMermaid && index && parent) {
mermaidCodeBlocks.push({ textNode, index, parent });
mermaidCodeBlockPromises.push({ textNode, index, parent });
}
});

if (mermaidCodeBlocks.length === 0) {
if (mermaidCodeBlockPromises.length === 0) {
return;
}

Expand All @@ -76,7 +76,7 @@ const rehypeMermaid: Plugin<[], Root> = () => {
const decoder = new TextDecoder();

await Promise.all(
mermaidCodeBlocks.map(async ({ textNode, index, parent }, blockIndex) => {
mermaidCodeBlockPromises.map(async ({ textNode, index, parent }, blockIndex) => {
const { data: svgBuffer } = await renderMermaid(browser, textNode.value, "svg");

const svgElem = decoder.decode(svgBuffer).replaceAll("my-svg", `my-svg-${blockIndex}`);
Expand All @@ -95,6 +95,8 @@ const rehypeMermaid: Plugin<[], Root> = () => {

await browser.close();
};

return transformer;
};

export default rehypeMermaid;

0 comments on commit 6894a69

Please sign in to comment.