-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathMarkdownRenderer.tsx
More file actions
77 lines (64 loc) · 2 KB
/
MarkdownRenderer.tsx
File metadata and controls
77 lines (64 loc) · 2 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import React, { useEffect } from 'react';
import classNames from 'classnames';
import copy from 'copy-to-clipboard';
import mergeRefs from './utils/mergeRefs';
import { iconPath as copyPath, svgTpl } from './icons/Copy';
import { iconPath as checkPath } from './icons/Check';
interface MarkdownRendererProps extends React.HTMLAttributes<HTMLDivElement> {
children?: string | null;
copyButtonProps?: React.HTMLAttributes<HTMLButtonElement>;
}
function appendCopyButton(
container?: HTMLDivElement | null,
buttonProps?: React.HTMLAttributes<HTMLButtonElement>
) {
if (!container) {
return;
}
const button = document.createElement('button');
button.className = 'btn-copy-code';
button.title = 'Copy code';
button.innerHTML = svgTpl(copyPath);
button.onclick = e => {
e.preventDefault();
const code = container?.querySelector('code')?.textContent;
const icon = button.querySelector('.copy-icon-path');
icon?.setAttribute('d', checkPath);
if (code) {
copy(code);
}
setTimeout(() => {
icon?.setAttribute('d', copyPath);
}, 2000);
};
if (buttonProps) {
Object.entries(buttonProps || {}).forEach(([key, value]) => {
button.setAttribute(key, value);
});
}
container?.appendChild(button);
}
const MarkdownRenderer = React.forwardRef(
(props: MarkdownRendererProps, ref: React.Ref<HTMLDivElement>) => {
const { children, className, copyButtonProps, ...rest } = props;
const mdRef = React.useRef<HTMLDivElement>(null);
useEffect(() => {
mdRef.current?.querySelectorAll('.rcv-code-renderer').forEach((el: any) => {
appendCopyButton(el, copyButtonProps);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (!children) {
return null;
}
return (
<div
{...rest}
ref={mergeRefs(mdRef, ref)}
className={classNames(className, 'rcv-markdown')}
dangerouslySetInnerHTML={{ __html: children }}
/>
);
}
);
export default MarkdownRenderer;