@@ -2,35 +2,48 @@ import React, { useEffect } from 'react';
22import classNames from 'classnames' ;
33import copy from 'copy-to-clipboard' ;
44import mergeRefs from './utils/mergeRefs' ;
5- import { iconPath as copyPath } from './icons/Copy' ;
5+ import { iconPath as copyPath , svgTpl } from './icons/Copy' ;
66import { iconPath as checkPath } from './icons/Check' ;
77
88interface MarkdownRendererProps extends React . HTMLAttributes < HTMLDivElement > {
99 children ?: string | null ;
1010}
1111
12+ function appendCopyButton ( container ?: HTMLDivElement | null ) {
13+ if ( ! container ) {
14+ return ;
15+ }
16+
17+ const button = document . createElement ( 'button' ) ;
18+ button . className =
19+ 'copy-code-button rs-btn-icon rs-btn-icon-circle rs-btn rs-btn-subtle rs-btn-xs' ;
20+ button . title = 'Copy code' ;
21+ button . innerHTML = svgTpl ( copyPath ) ;
22+ button . onclick = e => {
23+ e . preventDefault ( ) ;
24+ const code = container ?. querySelector ( 'code' ) ?. textContent ;
25+ const icon = button . querySelector ( '.copy-icon-path' ) ;
26+
27+ icon ?. setAttribute ( 'd' , checkPath ) ;
28+ if ( code ) {
29+ copy ( code ) ;
30+ }
31+
32+ setTimeout ( ( ) => {
33+ icon ?. setAttribute ( 'd' , copyPath ) ;
34+ } , 2000 ) ;
35+ } ;
36+ container ?. appendChild ( button ) ;
37+ }
38+
1239const MarkdownRenderer = React . forwardRef (
1340 ( props : MarkdownRendererProps , ref : React . Ref < HTMLDivElement > ) => {
1441 const { children, className, ...rest } = props ;
1542 const mdRef = React . useRef < HTMLDivElement > ( null ) ;
1643
1744 useEffect ( ( ) => {
18- mdRef . current ?. querySelectorAll ( '.copy-code-button' ) . forEach ( el => {
19- el . addEventListener ( 'click' , e => {
20- e . preventDefault ( ) ;
21-
22- const code = ( el . nextElementSibling as HTMLInputElement ) ?. value ;
23- const icon = el . querySelector ( '.copy-icon-path' ) ;
24-
25- icon ?. setAttribute ( 'd' , checkPath ) ;
26- if ( code ) {
27- copy ( code ) ;
28- }
29-
30- setTimeout ( ( ) => {
31- icon ?. setAttribute ( 'd' , copyPath ) ;
32- } , 2000 ) ;
33- } ) ;
45+ mdRef . current ?. querySelectorAll ( '.rcv-code-renderer' ) . forEach ( ( el : any ) => {
46+ appendCopyButton ( el ) ;
3447 } ) ;
3548 } , [ ] ) ;
3649
0 commit comments