-
-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathMarkdown.tsx
65 lines (55 loc) · 1.89 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
import React, { useContext, useEffect, useState } from 'react';
import { rehype } from 'rehype';
import rehypePrism from 'rehype-prism-plus';
import { IProps } from '../../Types';
import { EditorContext } from '../../Context';
function html2Escape(sHtml: string) {
return (
sHtml
.replace(
/[<&"]/g,
(c: string) => (({ '<': '<', '>': '>', '&': '&', '"': '"' }) as Record<string, string>)[c],
)
);
}
export interface MarkdownProps extends IProps, React.HTMLAttributes<HTMLPreElement> {}
export default function Markdown(props: MarkdownProps) {
const { prefixCls } = props;
const { markdown = '', highlightEnable, dispatch } = useContext(EditorContext);
const preRef = React.createRef<HTMLPreElement>();
const [mdStr, setMdStr] = useState('');
useEffect(() => {
if (preRef.current && dispatch) {
dispatch({ textareaPre: preRef.current });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
async function processMarkdown() {
if (!markdown) {
setMdStr('');
return;
}
let mdStr = `<pre class="language-markdown ${prefixCls}-text-pre wmde-markdown-color"><code class="language-markdown">${html2Escape(
String.raw`${markdown}`,
)}\n</code></pre>`;
if (highlightEnable) {
try {
mdStr = await rehype()
.data('settings', { fragment: true })
// https://github.com/uiwjs/react-md-editor/issues/593
// @ts-ignore
.use(rehypePrism, { ignoreMissing: true })
.process(mdStr)
.then((file) => file.toString());
} catch (error) {}
}
setMdStr(mdStr);
}
processMarkdown();
}, [markdown, highlightEnable, prefixCls]);
return React.createElement('div', {
className: 'wmde-markdown-color',
dangerouslySetInnerHTML: { __html: mdStr || '' },
});
}