feat: Add support for mathematical equations in Markdown

This commit is contained in:
Kom Senapati
2024-10-02 03:59:24 +00:00
parent 19315f72a0
commit ab77c4e616
3 changed files with 411 additions and 5 deletions

View File

@@ -4,6 +4,9 @@ import { useSelector } from 'react-redux';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/cjs/styles/prism';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
import 'katex/dist/katex.min.css';
import Alert from '../assets/alert.svg';
import DocsGPT3 from '../assets/cute_docsgpt3.svg';
@@ -62,6 +65,21 @@ const ConversationBubble = forwardRef<
</div>
);
} else {
const preprocessLaTeX = (content: string) => {
// Replace block-level LaTeX delimiters \[ \] with $$ $$
const blockProcessedContent = content.replace(
/\\\[(.*?)\\\]/gs,
(_, equation) => `$$${equation}$$`,
);
// Replace inline LaTeX delimiters \( \) with $ $
const inlineProcessedContent = blockProcessedContent.replace(
/\\\((.*?)\\\)/gs,
(_, equation) => `$${equation}$`,
);
return inlineProcessedContent;
};
bubble = (
<div
ref={ref}
@@ -225,7 +243,8 @@ const ConversationBubble = forwardRef<
)}
<ReactMarkdown
className="whitespace-pre-wrap break-normal leading-normal"
remarkPlugins={[remarkGfm]}
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[rehypeKatex]}
components={{
code(props) {
const { children, className, node, ref, ...rest } = props;
@@ -308,7 +327,7 @@ const ConversationBubble = forwardRef<
},
}}
>
{message}
{preprocessLaTeX(message)}
</ReactMarkdown>
</div>
</div>