1 import React from "react"
2 import {
3 CodeBlock,
4 CodeBlockMetaFields,
5 CodeBlockProps,
6 } from "@/components/CodeBlock"
7 import { InlineCode, InlineCodeProps } from "@/components/InlineCode"
8 import { MermaidDiagram } from "@/components/MermaidDiagram"
9 import { Npm2YarnCode } from "../Npm2YarnCode"
10 import { Npx2YarnCode } from "../Npx2YarnCode"
11
12 export type CodeMdxProps = {
13 className?: string
14 children?: React.ReactNode
15 inlineCodeProps?: Partial<InlineCodeProps>
16 codeBlockProps?: Partial<CodeBlockProps>
17 } & CodeBlockMetaFields
18
19 // due to how mdx handles code blocks
20 // it is required that a code block specify a language
21 // to be considered a block. Otherwise, it will be
22 // considered as inline code
23 export const CodeMdx = ({
24 className,
25 children,
26 inlineCodeProps = {},
27 codeBlockProps = {},
28 ...rest
29 }: CodeMdxProps) => {
30 if (!children) {
31 return <></>
32 }
33
34 const match = /language-(\w+)/.exec(className || "")
35
36 const codeContent = Array.isArray(children)
37 ? (children[0] as string)
38 : (children as string)
39
40 if (match) {
41 if (rest.npm2yarn) {
42 return <Npm2YarnCode npmCode={codeContent} {...rest} />
43 } else if (rest.npx2yarn || rest.npx2yarnExec) {
44 return (
45 <Npx2YarnCode
46 npxCode={codeContent}
47 {...rest}
48 isExecutable={!!rest.npx2yarnExec}
49 />
50 )
51 } else if (match[1] === "mermaid") {
52 return <MermaidDiagram diagramContent={codeContent} />
53 }
54 return (
55 <CodeBlock
56 source={codeContent}
57 lang={match[1]}
58 {...codeBlockProps}
59 {...rest}
60 />
61 )
62 }
63
64 return <InlineCode {...inlineCodeProps}>{codeContent}</InlineCode>
65 }