Skip to content

Commit a133864

Browse files
committed
Optimize markdown render for editor by throttling
1 parent eed9e41 commit a133864

File tree

1 file changed

+18
-18
lines changed

1 file changed

+18
-18
lines changed

src/components/common/MarkdownRender.tsx

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -226,15 +226,11 @@ const MarkdownRender: React.FC<MarkdownRenderProps> = ({
226226

227227
const [element, setElement] = useState<RenderedElement>(null);
228228
const [hasTagError, setHasTagError] = useState(false);
229+
const [delay, setDelay] = useState(25);
229230

230-
const applyElement = React.useMemo(() => {
231-
return throttle(250, (el: any) => {
232-
setElement(el);
233-
});
234-
}, []);
235-
236-
useEffect(() => {
237-
remark()
231+
const throttledUpdate = React.useMemo(() => {
232+
return throttle(delay, (markdown: string) => {
233+
remark()
238234
.use(remarkParse)
239235
.use(slug)
240236
.use(prismPlugin)
@@ -246,6 +242,11 @@ const MarkdownRender: React.FC<MarkdownRenderProps> = ({
246242
.use(katex)
247243
.use(stringify)
248244
.process(markdown, (err: any, file: any) => {
245+
const lines = markdown.split(/\r\n|\r|\n/).length
246+
const nextDelay = Math.max(Math.min(Math.floor(lines * 0.5), 1500), 22)
247+
if (nextDelay !== delay) {
248+
setDelay(nextDelay)
249+
}
249250
const html = String(file);
250251

251252
if (onConvertFinish) {
@@ -265,18 +266,17 @@ const MarkdownRender: React.FC<MarkdownRenderProps> = ({
265266
try {
266267
const el = parse(html);
267268
setHasTagError(false);
268-
applyElement(el);
269+
setElement(el);
269270
} catch (e) {}
270-
});
271-
}, [applyElement, editing, markdown, onConvertFinish]);
271+
}, 1)
272+
});
273+
}, [delay, editing, onConvertFinish]);
274+
272275

273-
// useEffect(() => {
274-
// if (editing) return;
275-
// const using = checkUsingMathjax(markdown);
276-
// if (using) {
277-
// loadMathjax();
278-
// }
279-
// }, [html, element, markdown, editing]);
276+
277+
useEffect(() => {
278+
throttledUpdate(markdown)
279+
}, [markdown, throttledUpdate]);
280280

281281
return (
282282
<Typography>

0 commit comments

Comments
 (0)