-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrap-root-element.js
More file actions
45 lines (40 loc) · 1.27 KB
/
wrap-root-element.js
File metadata and controls
45 lines (40 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { MDXProvider } from '@mdx-js/react';
import React from 'react';
import Code from './src/components/Code';
// Helper function to extract code block props
const preToCodeBlock = (preProps) => {
if (preProps.children && preProps.children.props) {
const {
children: codeString,
className = '',
...props
} = preProps.children.props;
// Check if this is a code block by looking for language- className
const matches = className.match(/language-(?<lang>.*)/);
if (matches && matches.groups && matches.groups.lang) {
return {
codeString:
typeof codeString === 'string' ? codeString.trim() : codeString,
className,
language: matches.groups.lang,
...props,
};
}
}
};
// components is its own object outside of render so that the references to
// components are stable
const components = {
pre: (preProps) => {
const props = preToCodeBlock(preProps);
// if there's a codeString and some props, we passed the test
if (props) {
return <Code {...props} />;
}
// it's possible to have a pre without a code in it
return <pre {...preProps} />;
},
};
export const wrapRootElement = ({ element }) => (
<MDXProvider components={components}>{element}</MDXProvider>
);