Skip to content
Snippets Groups Projects
Unverified Commit 84db7983 authored by Thuc Pham's avatar Thuc Pham Committed by GitHub
Browse files

feat: support display latex in chat markdown (#88)

parent 67a062af
No related branches found
No related tags found
No related merge requests found
---
"create-llama": patch
---
feat: support display latex in chat markdown
import "katex/dist/katex.min.css";
import { FC, memo } from "react"; import { FC, memo } from "react";
import ReactMarkdown, { Options } from "react-markdown"; import ReactMarkdown, { Options } from "react-markdown";
import rehypeKatex from "rehype-katex";
import remarkGfm from "remark-gfm"; import remarkGfm from "remark-gfm";
import remarkMath from "remark-math"; import remarkMath from "remark-math";
...@@ -12,11 +14,27 @@ const MemoizedReactMarkdown: FC<Options> = memo( ...@@ -12,11 +14,27 @@ const MemoizedReactMarkdown: FC<Options> = memo(
prevProps.className === nextProps.className, prevProps.className === nextProps.className,
); );
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;
};
export default function Markdown({ content }: { content: string }) { export default function Markdown({ content }: { content: string }) {
const processedContent = preprocessLaTeX(content);
return ( return (
<MemoizedReactMarkdown <MemoizedReactMarkdown
className="prose dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 break-words custom-markdown" className="prose dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 break-words custom-markdown"
remarkPlugins={[remarkGfm, remarkMath]} remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[rehypeKatex as any]}
components={{ components={{
p({ children }) { p({ children }) {
return <p className="mb-2 last:mb-0">{children}</p>; return <p className="mb-2 last:mb-0">{children}</p>;
...@@ -53,7 +71,7 @@ export default function Markdown({ content }: { content: string }) { ...@@ -53,7 +71,7 @@ export default function Markdown({ content }: { content: string }) {
}, },
}} }}
> >
{content} {processedContent}
</MemoizedReactMarkdown> </MemoizedReactMarkdown>
); );
} }
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
"remark-code-import": "^1.2.0", "remark-code-import": "^1.2.0",
"remark-gfm": "^3.0.1", "remark-gfm": "^3.0.1",
"remark-math": "^5.1.1", "remark-math": "^5.1.1",
"rehype-katex": "^7.0.0",
"supports-color": "^8.1.1", "supports-color": "^8.1.1",
"tailwind-merge": "^2.1.0" "tailwind-merge": "^2.1.0"
}, },
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment