1- import React , { useEffect } from 'react' ;
1+ import React , { useEffect , useImperativeHandle } from 'react' ;
22import ReactMarkdown , { ReactMarkdownProps } from 'react-markdown' ;
33import gfm from 'remark-gfm' ;
44import Prism from 'prismjs' ;
@@ -15,8 +15,13 @@ export type MarkdownPreviewProps = {
1515 onMouseOver ?: ( e : React . MouseEvent < HTMLDivElement > ) => void ;
1616} & ReactMarkdownProps ;
1717
18- const MarkdownPreview : React . FC < MarkdownPreviewProps > = ( props = { } as ReactMarkdownProps ) => {
19- const { className, source, style, onScroll, onMouseOver, ...other } = props ;
18+ export type MarkdownPreviewRef = {
19+ mdp : React . RefObject < HTMLDivElement > ;
20+ lang : string [ ] ,
21+ } & MarkdownPreviewProps ;
22+
23+ export default React . forwardRef < MarkdownPreviewRef , MarkdownPreviewProps > ( ( props , ref ) => {
24+ const { className, source, style, onScroll, onMouseOver, ...other } = props || { } ;
2025 const mdp = React . createRef < HTMLDivElement > ( ) ;
2126 const loadedLang = React . useRef < string [ ] > ( [ 'markup' ] ) ;
2227 useEffect ( ( ) => {
@@ -42,28 +47,27 @@ const MarkdownPreview: React.FC<MarkdownPreviewProps> = (props = {} as ReactMark
4247 }
4348 }
4449
50+ useImperativeHandle ( ref , ( ) => ( { ...props , lang : loadedLang . current , mdp } ) , [ mdp , props ] ) ;
51+
4552 const cls = `wmde-markdown wmde-markdown-color ${ className || '' } ` ;
4653 const reactMarkdownProps = {
4754 allowDangerousHtml : true ,
48- ...other ,
49- plugins : [ gfm , ...( other . plugins || [ ] ) ] ,
5055 allowNode : ( node , index , parent ) => {
51- const nodeany = node ;
52- if ( nodeany . type === 'html' && reactMarkdownProps . allowDangerousHtml ) {
56+ if ( node . type === 'html' && reactMarkdownProps . allowDangerousHtml ) {
5357 // filter style
5458 node . value = ( node . value as string ) . replace ( / < ( ( s t y l e | s c r i p t | l i n k | i n p u t | f o r m ) | \/ ( s t y l e | s c r i p t | l i n k | i n p u t | f o r m ) ) ( \s ? [ ^ > ] * > ) / gi, ( a : string ) => {
5559 return a . replace ( / [ < > ] / g, ( e : string ) => ( ( { '<' : '<' , '>' : '>' } as { [ key : string ] : string } ) [ e ] ) )
5660 } ) ;
5761 }
5862 return true ;
5963 } ,
64+ ...other ,
65+ plugins : [ gfm , ...( other . plugins || [ ] ) ] ,
6066 source : source || '' ,
6167 } as ReactMarkdownProps ;
6268 return (
6369 < div ref = { mdp } onScroll = { onScroll } onMouseOver = { onMouseOver } className = { cls } style = { style } >
6470 < ReactMarkdown { ...reactMarkdownProps } />
6571 </ div >
6672 ) ;
67- }
68-
69- export default MarkdownPreview ;
73+ } ) ;
0 commit comments