-
-
Notifications
You must be signed in to change notification settings - Fork 123
/
Markdown.tsx
67 lines (61 loc) · 1.9 KB
/
Markdown.tsx
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { FC, PropsWithChildren, useRef } from 'react';
import CodeLayout from 'react-code-preview-layout';
import { getMetaId, getURLParameters, CodeBlockData } from 'markdown-react-code-preview-loader';
import MarkdownPreview, { MarkdownPreviewProps } from '@uiw/react-markdown-preview';
import rehypeIgnore from 'rehype-ignore';
import { type Node } from 'unist';
import styled from 'styled-components';
const Preview = CodeLayout.Preview;
const Code = CodeLayout.Code;
const Toolbar = CodeLayout.Toolbar;
const CodeLayoutView = styled(CodeLayout)`
& + div.copied {
display: none !important;
}
`;
interface CodePreviewProps {
mdData?: CodeBlockData;
'data-meta'?: string;
node?: Node;
}
const CodePreview: FC<PropsWithChildren<CodePreviewProps>> = (props) => {
const $dom = useRef<HTMLDivElement>(null);
const { mdData, node, 'data-meta': meta, ...rest } = props;
const line = node?.position?.start.line;
const metaId = getMetaId(meta) || String(line);
const Child = mdData?.components[`${metaId}`];
if (metaId && typeof Child === 'function') {
const code = mdData?.data[metaId].value || '';
const param = getURLParameters(meta || '');
return (
<CodeLayoutView ref={$dom}>
<Preview>
<Child />
</Preview>
<Toolbar text={code}>{param.title || 'Example'}</Toolbar>
<Code>
<pre {...rest} />
</Code>
</CodeLayoutView>
);
}
return <code {...rest} />;
};
interface MarkdownProps extends MarkdownPreviewProps {
mdData?: CodeBlockData;
}
export default function Markdown(props: MarkdownProps) {
const { mdData, ...rest } = props;
return (
<MarkdownPreview
{...rest}
style={{ paddingTop: 30 }}
// disableCopy={true}
rehypePlugins={[rehypeIgnore]}
source={props.source || ''}
components={{
code: (props) => <CodePreview {...props} mdData={mdData} />,
}}
/>
);
}