UNPKG

@theguild/remark-mermaid

Version:

Remark plugin for replacing ```mermaid code blocks with react `<Mermaid />` component

74 lines (73 loc) 1.91 kB
import { createRequire } from "node:module"; import { visit } from "unist-util-visit"; const require2 = createRequire(import.meta.url); const COMPONENT_PATH = require2.resolve("@theguild/remark-mermaid/mermaid"); const COMPONENT_NAME = "Mermaid"; const MERMAID_IMPORT_AST = { type: "mdxjsEsm", data: { estree: { body: [ { type: "ImportDeclaration", specifiers: [ { type: "ImportSpecifier", imported: { type: "Identifier", name: COMPONENT_NAME }, local: { type: "Identifier", name: COMPONENT_NAME } } ], source: { type: "Literal", value: COMPONENT_PATH } } ] } } }; const getMermaidElementAST = (value) => ({ type: "mdxJsxFlowElement", name: COMPONENT_NAME, attributes: [ { type: "mdxJsxAttribute", name: "chart", value: { type: "mdxJsxAttributeValueExpression", data: { estree: { body: [ { type: "ExpressionStatement", expression: { type: "TemplateLiteral", expressions: [], quasis: [ { type: "TemplateElement", value: { raw: value } } ] } } ] } } } } ] }); const remarkMermaid = () => (ast, _file, done) => { const codeblocks = []; visit(ast, { type: "code", lang: "mermaid" }, (node, index, parent) => { codeblocks.push([node, index, parent]); }); if (codeblocks.length !== 0) { for (const [node, index, parent] of codeblocks) { parent.children.splice(index, 1, getMermaidElementAST(node.value)); } ast.children.unshift(MERMAID_IMPORT_AST); } done(); }; export { remarkMermaid };