Skip to content

Commit 089752e

Browse files
authored
Issue 50: Fixing inline code blocks (#55)
1 parent 2dd4cb5 commit 089752e

1 file changed

Lines changed: 33 additions & 9 deletions

File tree

components/MDXRenderer.tsx

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -128,15 +128,32 @@ const markdownComponents = (repositoryHomepage: assets.GithubURL) => ({
128128
{props.children}
129129
</Paragraph>
130130
),
131-
code: (props: React.ComponentProps<any>) => (
132-
<CodeBlock variant="default" content={String(props.children)} showCopyButton />
133-
),
134-
inlineCode: (props: React.ComponentProps<any>) => (
135-
<CodeBlock variant="inline" content={String(props.children)} />
136-
),
137-
kbd: (props: React.ComponentProps<any>) => (
138-
<CodeBlock variant="inline" content={String(props.children)} />
139-
),
131+
code: (props: React.ComponentProps<any>) => {
132+
// The `code` component can be used for single-line or multi-line code blocks. Determine which to use.
133+
// Usually multi-line blocks are wrapped in `pre` and are handled that way instead of this.
134+
// className will exist if this is a code block and the syntax language is defined.
135+
if (props.className) {
136+
return defaultCodeBlock(String(props.children));
137+
}
138+
return (<CodeBlock variant="inline" content={String(props.children)} />);
139+
},
140+
pre: (props: React.ComponentProps<any>) => {
141+
// The <pre> block is how multi-line code-blocks are rendered. This unpacks it and renders it appopriately.
142+
// Ensure we have exactly one child:
143+
if (!props.children) {
144+
return null; // No child --> render nothing
145+
}
146+
147+
const child = React.Children.only(props.children);
148+
149+
// Check if the child is a function that makes a <code> element:
150+
if ( React.isValidElement(child) && typeof child.type === "function" && (child.type as Function).name === "code" ) {
151+
const codeChildrenProps: React.ComponentProps<any> = child.props;
152+
return defaultCodeBlock(String(codeChildrenProps.children || "")); // Fall back to empty string if there is no code.
153+
}
154+
// If there is no <code> child, return null. There should be a child <code> element.
155+
return null;
156+
},
140157
span: (props: React.ComponentProps<any>) => (
141158
<Text display="flex">{props.children}</Text>
142159
),
@@ -148,6 +165,13 @@ const markdownComponents = (repositoryHomepage: assets.GithubURL) => ({
148165
),
149166
});
150167

168+
/**
169+
* Multiple components can create a Default CodeBlock component, so define it only once:
170+
*/
171+
const defaultCodeBlock = (codeContent: string) => {
172+
return <CodeBlock variant="default" content={codeContent} showCopyButton />;
173+
}
174+
151175
export const MDXRenderer = (props: Props) => (
152176
<MDXRemote
153177
{...props.mdxSource}

0 commit comments

Comments
 (0)