Skip to content

Commit

Permalink
Allow empty code blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
slorber committed Jan 5, 2024
1 parent ca09f23 commit e5116f5
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 6 deletions.
14 changes: 10 additions & 4 deletions packages/docusaurus-theme-classic/src/theme/MDXComponents/Code.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@ import React from 'react';
import CodeBlock from '@theme/CodeBlock';
import type {Props} from '@theme/MDXComponents/Code';

export default function MDXCode(props: Props): JSX.Element {
const shouldBeInline = React.Children.toArray(props.children).every(
(el) => typeof el === 'string' && !el.includes('\n'),
function shouldBeInline(props: Props) {
return (
typeof props.children !== 'undefined' &&
React.Children.toArray(props.children).every(
(el) => typeof el === 'string' && !el.includes('\n'),
)
);
}

return shouldBeInline ? (
export default function MDXCode(props: Props): JSX.Element {
const inline = shouldBeInline(props);
return inline ? (
<code {...props} />
) : (
<CodeBlock {...(props as ComponentProps<typeof CodeBlock>)} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ declare module '@theme/Playground' {
type LiveProviderProps = React.ComponentProps<typeof LiveProvider>;

export interface Props extends CodeBlockProps, LiveProviderProps {
children: string;
// Allow empty live playgrounds
children?: string;
}
export default function Playground(props: LiveProviderProps): JSX.Element;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export default function Playground({
return (
<div className={styles.playgroundContainer}>
<LiveProvider
code={children.replace(/\n$/, '')}
code={children?.replace(/\n$/, '')}
noInline={noInline}
transformCode={transformCode ?? DEFAULT_TRANSFORM_CODE}
theme={prismTheme}
Expand Down
30 changes: 30 additions & 0 deletions website/_dogfooding/_pages tests/code-block-tests.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -458,3 +458,33 @@ See https://github.com/facebook/docusaurus/issues/9517
</head>
</html>
```
## Empty code blocks edge cases
Empty inline code block: ``
Single space inline code block: ` `
Empty code block
{/* prettier-ignore */}
```
```
Empty 1 line code block
```

```
Empty 2 line code block
```

```
Empty live code block
```js live

```

0 comments on commit e5116f5

Please sign in to comment.