perf: Lazy load rehype-raw and react-markdown (#29855)
This commit is contained in:
parent
f1136b57dd
commit
5b5f448af0
|
|
@ -16,10 +16,8 @@
|
||||||
* specific language governing permissions and limitations
|
* specific language governing permissions and limitations
|
||||||
* under the License.
|
* under the License.
|
||||||
*/
|
*/
|
||||||
import { useMemo } from 'react';
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
import ReactMarkdown from 'react-markdown';
|
|
||||||
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
|
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
|
||||||
import rehypeRaw from 'rehype-raw';
|
|
||||||
import remarkGfm from 'remark-gfm';
|
import remarkGfm from 'remark-gfm';
|
||||||
import { mergeWith, isArray } from 'lodash';
|
import { mergeWith, isArray } from 'lodash';
|
||||||
import { FeatureFlag, isFeatureEnabled } from '../utils';
|
import { FeatureFlag, isFeatureEnabled } from '../utils';
|
||||||
|
|
@ -45,11 +43,21 @@ function SafeMarkdown({
|
||||||
htmlSchemaOverrides = {},
|
htmlSchemaOverrides = {},
|
||||||
}: SafeMarkdownProps) {
|
}: SafeMarkdownProps) {
|
||||||
const escapeHtml = isFeatureEnabled(FeatureFlag.EscapeMarkdownHtml);
|
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 = useMemo(() => {
|
||||||
const rehypePlugins: any = [];
|
const rehypePlugins: any = [];
|
||||||
if (!escapeHtml) {
|
if (!escapeHtml && rehypeRawPlugin) {
|
||||||
rehypePlugins.push(rehypeRaw);
|
rehypePlugins.push(rehypeRawPlugin);
|
||||||
if (htmlSanitization) {
|
if (htmlSanitization) {
|
||||||
const schema = getOverrideHtmlSchema(
|
const schema = getOverrideHtmlSchema(
|
||||||
defaultSchema,
|
defaultSchema,
|
||||||
|
|
@ -59,7 +67,11 @@ function SafeMarkdown({
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return rehypePlugins;
|
return rehypePlugins;
|
||||||
}, [escapeHtml, htmlSanitization, htmlSchemaOverrides]);
|
}, [escapeHtml, htmlSanitization, htmlSchemaOverrides, rehypeRawPlugin]);
|
||||||
|
|
||||||
|
if (!ReactMarkdown || !rehypeRawPlugin) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
// React Markdown escapes HTML by default
|
// React Markdown escapes HTML by default
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue