diff --git a/src/index.tsx b/src/index.tsx index a98e1fa4..8d06bf22 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,4 +1,4 @@ -import React, { useEffect } from 'react'; +import React, { useEffect, useImperativeHandle } from 'react'; import ReactMarkdown, { ReactMarkdownProps } from 'react-markdown'; import gfm from 'remark-gfm'; import Prism from 'prismjs'; @@ -15,8 +15,13 @@ export type MarkdownPreviewProps = { onMouseOver?: (e: React.MouseEvent) => void; } & ReactMarkdownProps; -const MarkdownPreview: React.FC = (props = {} as ReactMarkdownProps) => { - const { className, source, style, onScroll, onMouseOver, ...other } = props; +export type MarkdownPreviewRef = { + mdp: React.RefObject; + lang: string[], +} & MarkdownPreviewProps; + +export default React.forwardRef((props, ref) => { + const { className, source, style, onScroll, onMouseOver, ...other } = props || {}; const mdp = React.createRef(); const loadedLang = React.useRef(['markup']); useEffect(() => { @@ -42,14 +47,13 @@ const MarkdownPreview: React.FC = (props = {} as ReactMark } } + useImperativeHandle(ref, () => ({ ...props, lang: loadedLang.current, mdp }), [mdp, props]); + const cls = `wmde-markdown wmde-markdown-color ${className || ''}`; const reactMarkdownProps = { allowDangerousHtml: true, - ...other, - plugins: [gfm, ...(other.plugins || [])], allowNode: (node, index, parent) => { - const nodeany = node; - if (nodeany.type === 'html' && reactMarkdownProps.allowDangerousHtml) { + if (node.type === 'html' && reactMarkdownProps.allowDangerousHtml) { // filter style node.value = (node.value as string).replace(/<((style|script|link|input|form)|\/(style|script|link|input|form))(\s?[^>]*>)/gi, (a: string) => { return a.replace(/[<>]/g, (e: string) => (({ '<': '<', '>': '>' } as { [key: string]: string })[e])) @@ -57,6 +61,8 @@ const MarkdownPreview: React.FC = (props = {} as ReactMark } return true; }, + ...other, + plugins: [gfm, ...(other.plugins || [])], source: source || '', } as ReactMarkdownProps; return ( @@ -64,6 +70,4 @@ const MarkdownPreview: React.FC = (props = {} as ReactMark ); -} - -export default MarkdownPreview; +}); diff --git a/website/App.tsx b/website/App.tsx index 572d01ac..ed0ddfd7 100644 --- a/website/App.tsx +++ b/website/App.tsx @@ -4,13 +4,14 @@ import Github from '@uiw/react-shields/lib/esm/github'; import Npm from '@uiw/react-shields/lib/esm/npm'; import logo from './logo.svg'; import './App.css'; -import MarkdownPreview from '../'; +import MarkdownPreview, { MarkdownPreviewRef } from '../'; import MDStr from '../README.md'; let val = 1; export default () => { const [value, setValue] = useState(''); + const ref = React.createRef(); return (
@@ -24,15 +25,14 @@ export default () => {

- + +