perf: Lazy load rehype-raw and react-markdown (#29855)

This commit is contained in:
Kamil Gabryjelski 2024-08-05 17:19:06 +02:00 committed by GitHub
parent f1136b57dd
commit 5b5f448af0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 18 additions and 6 deletions

View File

@ -16,10 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
import { useMemo } from 'react';
import ReactMarkdown from 'react-markdown';
import { useEffect, useMemo, useState } from 'react';
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
import rehypeRaw from 'rehype-raw';
import remarkGfm from 'remark-gfm';
import { mergeWith, isArray } from 'lodash';
import { FeatureFlag, isFeatureEnabled } from '../utils';
@ -45,11 +43,21 @@ function SafeMarkdown({
htmlSchemaOverrides = {},
}: SafeMarkdownProps) {
const escapeHtml = isFeatureEnabled(FeatureFlag.EscapeMarkdownHtml);
const [rehypeRawPlugin, setRehypeRawPlugin] = useState<any>(null);
const [ReactMarkdown, setReactMarkdown] = useState<any>(null);
useEffect(() => {
Promise.all([import('rehype-raw'), import('react-markdown')]).then(
([rehypeRaw, ReactMarkdown]) => {
setRehypeRawPlugin(() => rehypeRaw.default);
setReactMarkdown(() => ReactMarkdown.default);
},
);
}, []);
const rehypePlugins = useMemo(() => {
const rehypePlugins: any = [];
if (!escapeHtml) {
rehypePlugins.push(rehypeRaw);
if (!escapeHtml && rehypeRawPlugin) {
rehypePlugins.push(rehypeRawPlugin);
if (htmlSanitization) {
const schema = getOverrideHtmlSchema(
defaultSchema,
@ -59,7 +67,11 @@ function SafeMarkdown({
}
}
return rehypePlugins;
}, [escapeHtml, htmlSanitization, htmlSchemaOverrides]);
}, [escapeHtml, htmlSanitization, htmlSchemaOverrides, rehypeRawPlugin]);
if (!ReactMarkdown || !rehypeRawPlugin) {
return null;
}
// React Markdown escapes HTML by default
return (