Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix support for asynchronous plugins in rehypePlugins #670

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 32 additions & 25 deletions core/src/components/TextArea/Markdown.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext, useEffect } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import { rehype } from 'rehype';
import rehypePrism from 'rehype-prism-plus';
import { IProps } from '../../Types';
Expand All @@ -7,12 +7,6 @@ import { EditorContext } from '../../Context';
function html2Escape(sHtml: string) {
return (
sHtml
// .replace(/```(\w+)?([\s\S]*?)(\s.+)?```/g, (str: string) => {
// return str.replace(
// /[<&"]/g,
// (c: string) => (({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' } as Record<string, string>)[c]),
// );
// })
.replace(
/[<&"]/g,
(c: string) => (({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }) as Record<string, string>)[c],
Expand All @@ -26,30 +20,43 @@ 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
}, []);
if (!markdown) {
return <pre ref={preRef} className={`${prefixCls}-text-pre wmde-markdown-color`} />;
}
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 = rehype()
.data('settings', { fragment: true })
// https://github.com/uiwjs/react-md-editor/issues/593
// @ts-ignore
.use(rehypePrism, { ignoreMissing: true })
.processSync(mdStr)
.toString();
} catch (error) {}
}

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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

An error occurred in the example. @vishwamartur

.then((file) => file.toString());
} catch (error) {}
}

setMdStr(mdStr);
}

processMarkdown();
}, [markdown, highlightEnable, prefixCls]);

return React.createElement('div', {
className: 'wmde-markdown-color',
Expand Down
45 changes: 45 additions & 0 deletions test/editor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,48 @@ it('MDEditor KeyboardEvent onHeightChange', async () => {
expect(handleChange).lastReturnedWith(500);
expect(handleChange).toHaveLength(3);
});

it('MDEditor supports asynchronous plugins', async () => {
const MyComponent = () => {
const [value, setValue] = React.useState('**Hello world!!!**');
return (
<MDEditor
value={value}
textareaProps={{
title: 'test',
}}
previewOptions={{
rehypePlugins: [
async () => {
return (tree) => {
// Example async plugin that adds a class to the first node
return new Promise((resolve) => {
setTimeout(() => {
if (tree.children && tree.children.length > 0) {
tree.children[0].properties = {
...tree.children[0].properties,
className: 'async-plugin',
};
}
resolve(tree);
}, 100);
});
};
},
],
}}
onChange={(value) => {
setValue(value || '');
}}
/>
);
};
render(<MyComponent />);
const inputNode = screen.getByTitle('test');
inputNode.focus();
fireEvent.change(inputNode, { target: { value: '# title' } });
inputNode.blur();
await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for async plugin to complete
const previewNode = screen.getByText('title');
expect(previewNode).toHaveClass('async-plugin');
});
2 changes: 2 additions & 0 deletions www/src/Example.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { Fragment } from 'react';
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
import rehypePrettyCode from 'rehype-pretty-code';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rehype-pretty-code dependency is not included in package.json. @vishwamartur

import MDEditor, { MDEditorProps } from '@uiw/react-md-editor';
import styled from 'styled-components';

Expand Down Expand Up @@ -51,6 +52,7 @@ const Example = (props = {} as { mdStr: string }) => {
},
},
],
rehypePrettyCode,
],
}}
height={400}
Expand Down