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

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

Merged
merged 1 commit into from
Aug 5, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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,
Expand All @@ -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 (
Expand Down
Loading